package com.wf; import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import java.awt.*; class PaintUserData
{
public static Color _color = Color.BLACK; } class ProjectTree extends JTree implements TreeSelectionListener
{ private JPanel _panel; public ProjectTree(JPanel panel) {
addTreeSelectionListener(this);
_panel = panel;
} @Override
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getNewLeadSelectionPath();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent(); if (node.getUserObject().equals("red"))
{
PaintUserData._color = Color.red; }
else if (node.getUserObject().equals("blue"))
{
PaintUserData._color = Color.blue; }
else if (node.getUserObject().equals("yellow"))
{
PaintUserData._color = Color.yellow;
}
else if (node.getUserObject().equals("violet"))
{
PaintUserData._color = Color.CYAN;
}
else
{
PaintUserData._color = Color.black; }
_panel.repaint();
} } class PaintPanel extends JPanel
{ public PaintPanel() { } @Override
public void paint(Graphics g) {
super.paint(g); g.setColor(PaintUserData._color);
g.drawLine(0, 0, 400, 400); } } class MainWidget extends JComponent
{
private GridBagConstraints _gbScrollPane;
private GridBagConstraints _gbPaintPanel;
private GridBagLayout _layout; private JScrollPane _scrollPane;
private ProjectTree _projectTree;
private PaintPanel _paintPanel;
public MainWidget() {
_gbScrollPane = new GridBagConstraints();
_gbPaintPanel = new GridBagConstraints(); _gbScrollPane.weightx = 0.1;
_gbScrollPane.weighty = 1;
_gbScrollPane.gridx = 0;
_gbScrollPane.gridy = 0;
_gbScrollPane.fill = GridBagConstraints.BOTH; _gbPaintPanel.weightx = 0.9;
_gbPaintPanel.weighty = 0;
_gbPaintPanel.gridx = 1;
_gbPaintPanel.gridy = 0;
_gbPaintPanel.fill = GridBagConstraints.BOTH; _layout = new GridBagLayout();
setLayout(_layout); _scrollPane = new JScrollPane(); _paintPanel = new PaintPanel();
_projectTree = new ProjectTree(_paintPanel); _scrollPane.getViewport().add(_projectTree);
add(_scrollPane, _gbScrollPane); add(_paintPanel, _gbPaintPanel); } }
public class Test01 extends JFrame
{
private MainWidget _mainWidget; public Test01() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); _mainWidget = new MainWidget(); getContentPane().add(_mainWidget);
} public static void main(String[] args) throws Exception{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() { Test01 f = new Test01();
f.setSize(1024, 800);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}