我正在使用JTree
,它正在使用DefaultTreeModel
。这个树模型内部有一些节点,当我单击一个节点时,我会获得该节点的信息,并更改背景颜色以显示该节点已被选中。
当我单击树上的任何位置时,是否可以调用树以清除选择?通过清除选择,我将能够再次更改背景色,但是当我从树中单击时,我不知道如何或在何处使用树的clearSelection()
方法。
这是我正在使用的代码:
示例:
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class JTreeSelectDeselect {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JTree tree = new JTree();
tree.setCellRenderer(new DeselectTreeCellRenderer());
panel.add(tree, BorderLayout.LINE_START);
panel.add(new JScrollPane(new JTextArea(10, 30)));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
class DeselectTreeCellRenderer extends DefaultTreeCellRenderer {
@Override
public Color getBackgroundSelectionColor() {
return new Color(86, 92, 160);
}
@Override
public Color getBackground() {
return (null);
}
@Override
public Color getBackgroundNonSelectionColor() {
return new Color(23, 27, 36);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
setForeground(new Color(225, 225, 221, 255));
setOpaque(false);
return this;
}
}
我在这里展示了如何使用树模型创建节点并将其添加到树中以及如何设置自定义TreeCellRenderer
。
在单元格渲染器中,我用特定的颜色绘制所选节点,如果取消选中该节点,则使用另一种颜色绘制。当我更改节点的选择时,它们的背景可以正确绘制,但是当我在树的外部单击时,不会取消选择选定的节点,因此不会使用在单元渲染器中建立的特定颜色来绘制它。
当我在树外单击时,是否可以取消选择节点?
是否有人知道,有一种方法可以通过TreeCellRenderer
中的复选框来更改某些叶子?有一些孩子作为标签,另一些孩子作为复选框。因为当我尝试添加复选框时(如我所预期的那样),它表明复选框不是DefaultMutableTreeNode
对象,并且我无法将其添加到树模型中。
答案 0 :(得分:4)
首先,如果您只想更改某些颜色,则无需继承DefaultTreeCellRenderer。您可以创建一个新的颜色,根据需要设置颜色并将其设置为树。在下面的代码示例中,我已经在getDefaultTreeCellRenderer()中完成了此操作。
您的面板包含两个元素:树和文本区域。 为了实现您所需的功能,我在树上添加了鼠标侦听器和焦点侦听器:
我们需要两个侦听器,因为第一个侦听器仅在您单击树及其周围时才被触发,而在文本区域则不被触发,而第二个侦听器则在您离开树形区域并聚焦于文本区域时被触发。
import javax.swing.*;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class JTreeSelectDeselect {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JTree tree = new JTree();
tree.setCellRenderer(getDefaultTreeCellRenderer());
tree.addMouseListener(getMouseListener(tree));
tree.addFocusListener(getFocusListener(tree));
panel.add(tree, BorderLayout.LINE_START);
panel.add(new JScrollPane(new JTextArea(10, 30)));
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private static DefaultTreeCellRenderer getDefaultTreeCellRenderer() {
DefaultTreeCellRenderer defaultTreeCellRenderer = new DefaultTreeCellRenderer();
defaultTreeCellRenderer.setBackgroundSelectionColor(new Color(86, 92, 160));
defaultTreeCellRenderer.setBackgroundNonSelectionColor(new Color(135, 151, 53));
defaultTreeCellRenderer.setBackground(new Color(225, 225, 221, 255));
defaultTreeCellRenderer.setForeground(new Color(225, 225, 221, 255));
return defaultTreeCellRenderer;
}
private static FocusListener getFocusListener(final JTree tree) {
return new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
System.out.println("focus lost");
tree.clearSelection();
}
};
}
private static MouseListener getMouseListener(final JTree tree) {
return new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("mouse clicked");
if(tree.getRowForLocation(e.getX(),e.getY()) == -1) {
System.out.println("clicked outside a specific cell");
tree.clearSelection();
}
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
};
}
}
答案 1 :(得分:2)
如果要在其他位置单击鼠标时取消选择树中所有选定的节点,则需要在用户单击其他位置时得到通知。要获取它,您可以使用全局事件侦听器(Toolkit.getDefaultToolkit().addAWTEventListener()
)。
如果要在树中显示某些复选框,则需要一个自定义单元格渲染器,条件返回该复选框。另外,您还需要一个数据容器来保存是否选择了该节点,最后还需要一个例程,以在单击该节点时更新数据模型。最后一件事通常是由单元格编辑器提供的(有关editors and renderes的文章中有更多信息),但是对于您而言,使用我们之前安装的全局鼠标侦听器更容易。
当然,我的示例中包含一些“摇摆魔术”,所以当您不了解某些内容时,请随时向我询问;)
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
/**
* <code>JTreeDeselected</code>.
*/
public class JTreeSelectDeselect {
private final JTree tree = new JTree();
// model to hold nodes that must be presented as check boxes
// and whether the check boxes are selected
private final Map<Object, Boolean> checkMap = new HashMap<>();
// listener as method reference
private AWTEventListener awtListener = this::mouseClicked;
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTreeSelectDeselect()::start);
}
private void start() {
checkMap.put("football", true);
checkMap.put("soccer", false);
checkMap.put("violet", true);
checkMap.put("yellow", false);
checkMap.put("pizza", true);
checkMap.put("ravioli", false);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
// JTree tree = new JTree();
tree.setCellRenderer(new DeselectTreeCellRenderer(checkMap));
panel.add(new JScrollPane(tree), BorderLayout.LINE_START);
panel.add(new JScrollPane(new JTextArea(10, 30)));
frame.add(panel);
// register global listener
Toolkit.getDefaultToolkit().addAWTEventListener(awtListener, AWTEvent.MOUSE_EVENT_MASK);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void mouseClicked(AWTEvent evt) {
if (evt instanceof MouseEvent) {
MouseEvent me = (MouseEvent) evt;
if (me.getID() == MouseEvent.MOUSE_PRESSED) {
if (me.getComponent().equals(tree)) {
TreePath path = tree.getPathForLocation(me.getX(), me.getY());
if (path == null) {
tree.clearSelection();
} else {
// update check box value
String pathString = Objects.toString(path.getLastPathComponent(), "");
Boolean val = checkMap.get(pathString);
if (val != null) {
checkMap.put(pathString, !val);
((DefaultTreeModel) tree.getModel()).valueForPathChanged(path, pathString);
}
}
} else {
tree.clearSelection();
}
}
}
}
}
class DeselectTreeCellRenderer extends DefaultTreeCellRenderer {
private final JCheckBox checkBox = new JCheckBox();
private final Map<Object, Boolean> checkMap;
public DeselectTreeCellRenderer(Map<Object, Boolean> checkMap) {
this.checkMap = checkMap;
}
@Override
public Color getBackgroundSelectionColor() {
return new Color(86, 92, 160);
}
@Override
public Color getBackground() {
return (null);
}
@Override
public Color getBackgroundNonSelectionColor() {
return new Color(23, 27, 36);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean exp, boolean leaf, int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
setForeground(new Color(225, 225, 221, 255));
setOpaque(false);
// if our "check model" contains an entry for the node,
// present the node as check box
if (checkMap.containsKey(Objects.toString(value))) {
checkBox.setOpaque(true);
checkBox.setSelected(Boolean.TRUE == checkMap.get(Objects.toString(value)));
checkBox.setBackground(sel ? getBackgroundSelectionColor() : getBackgroundNonSelectionColor());
checkBox.setForeground(getForeground());
checkBox.setFont(getFont());
checkBox.setBorder(getBorder());
checkBox.setText(getText());
return checkBox;
}
return this;
}
}
答案 2 :(得分:2)
Java AWT软件包中的Robot类用于生成本机系统输入事件,用于测试自动化,自运行演示以及需要控制鼠标和键盘的其他应用程序。 Robot的主要目的是促进Java平台实现的自动化测试。简而言之,该类提供了对鼠标和键盘设备的控制。在下面的代码段中,“机器人”已用于捕获事件并清除树中的选择。
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.TreePath;
public class TreeDeselectionTest {
JTree createdTreeInstance = new JTree();
TreePath pathSelectionInstance;
Robot robotInstance;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TreeDeselectionTest().createTreeAndCaptureEvents();
}
});
}
public void createTreeAndCaptureEvents() {
try {
robotInstance = new Robot();
} catch (AWTException exceptionInstance) {
exceptionInstance.printStackTrace();
}
createdTreeInstance.setShowsRootHandles(false);
createdTreeInstance.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent eventMousePressInstance) {
if (robotInstance != null && pathSelectionInstance != null && eventMousePressInstance.getButton() == MouseEvent.BUTTON1) {
createdTreeInstance.clearSelection();
robotInstance.mousePress(InputEvent.BUTTON1_MASK);
robotInstance.mouseRelease(InputEvent.BUTTON1_MASK);
}
pathSelectionInstance = createdTreeInstance.getSelectionPath();
}
});
JFrame frameConetnds = new JFrame();
frameConetnds.setContentPane(new JScrollPane(createdTreeInstance));
frameConetnds.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameConetnds.setSize(400, 400);
frameConetnds.setLocationRelativeTo(null);
frameConetnds.setVisible(true);
}
}