gpt4 book ai didi

java - JTree 单元格编辑器接收鼠标点击的方式因操作系统而异

转载 作者:行者123 更新时间:2023-12-03 01:37:33 28 4
gpt4 key购买 nike

我创建了一个树单元渲染器/编辑器框架,诚然有点老套,但它在 Windows 和 Linux 上运行得很好。下图展示了一个示例设置。

enter image description here

目标是,如果用户单击图像(数字)1 或 2,则应用程序会响应该单击,但不会选择树行。如果用户单击一两个文本,应用程序会响应该单击并选择树行。我实现这个的方式再次有点hacky。基本上,当用户单击树行时,会显示编辑器组件(看起来与渲染器组件相同),并且编辑器组件有一个鼠标监听器,可以确定用户在行中单击的位置。

事实上,它在 Windows/Linux 上运行依赖于我一直认为似乎不太可靠的东西。基本上,如果您单击该行一次,则单击会 (a) 调出编辑器并 (b) 激活编辑器组件上的鼠标监听器。这就是我想要的方式!然而,当您尝试在 Mac OSX(10.6.2,如果重要的话)上运行该应用程序时,上述脆弱的假设不再成立。任何时候你想与树交互,你都必须点击两次(一次激活编辑器,再一次激活鼠标监听器)。

下面的 SSCCE 可以重现该行为。当然,如果您没有 OSX,则无法重现不需要的行为,但也许您仍然可以推荐一种更聪明的方法来实现我的目标。观察控制台中的 sysout 消息,该消息指示您单击树的各个部分时发生的情况。

哦,SSCCE 引用了这两张图片:

image 1 iamge 2

package TreeTest;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.util.EventObject;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

@SuppressWarnings("serial")
public class TreeTest extends JComponent {

private JFrame frame;
private DefaultTreeModel treeModel;
private DefaultMutableTreeNode root;
private JTree tree;

public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Throwable e) {
e.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TreeTest window = new TreeTest();
window.frame.setVisible(true);
window.frame.requestFocusInWindow();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

public TreeTest() {
initialize();
}

private void initialize() {
frame = new JFrame("Tree Test");
frame.setBounds(400, 400, 250, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

root = new DefaultMutableTreeNode("root");
treeModel = new DefaultTreeModel(root);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setRootVisible(false);
tree.setShowsRootHandles(false);
tree.setCellRenderer(new TreeRenderer());
tree.setCellEditor(new TreeEditor());
tree.putClientProperty("JTree.lineStyle", "None");
tree.setBackground(Color.white);

treeModel.insertNodeInto(new DefaultMutableTreeNode("two"), root, 0);
treeModel.insertNodeInto(new DefaultMutableTreeNode("one"), root, 0);

TreeNode[] nodes = treeModel.getPathToRoot(root);
tree.expandPath(new TreePath(nodes));
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
System.out.println("SELECTION CHANGED!");
}
});

frame.getContentPane().add(tree);
}

public class TreeComponent extends JPanel {

public TreeComponent(JLabel numIcon, JLabel numText) {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.add(numIcon);
this.add(numText);
}
}

public class TreeRenderer implements TreeCellRenderer {

private ImageIcon oneIcon;
private ImageIcon twoIcon;

public TreeRenderer() {
try {
oneIcon = new ImageIcon(ImageIO.read(
new URL("/image/1dp6a.png")));
twoIcon = new ImageIcon(ImageIO.read(
new URL("/image/UteiP.png")));
} catch (Exception e) {
e.printStackTrace();
}

}

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
JLabel numIcon = new JLabel();
numIcon.setAlignmentX(JLabel.CENTER_ALIGNMENT);
numIcon.setAlignmentY(JLabel.CENTER_ALIGNMENT);
numIcon.setBorder(new EmptyBorder(0, 0, 0, 4));

JLabel numText = new JLabel();

TreeComponent comp = new TreeComponent(numIcon, numText);

String str = (String) ((DefaultMutableTreeNode) value).getUserObject();
if (str.equals("one")) {
numIcon.setIcon(oneIcon);
numText.setText("one");
} else if (str.equals("two")) {
numIcon.setIcon(twoIcon);
numText.setText("two");
}

numText.setOpaque(true);
if (selected) {
numText.setBackground(new Color(209, 230, 255));
numText.setBorder(new LineBorder(
new Color(132, 172, 221), 1, false));
} else {
numText.setBackground(Color.white);
numText.setBorder(new LineBorder(Color.white, 1, false));
}
comp.setFocusable(false);
comp.setBackground(Color.white);
return comp;
}
}

public class TreeEditor implements TreeCellEditor {

private TreeRenderer rend;
private TreeComponent editorComponent;
private JTree tree;
private DefaultTreeModel treeModel;
private DefaultMutableTreeNode node;
private String str;

public TreeEditor() {
rend = new TreeRenderer();
}

@Override
public Component getTreeCellEditorComponent(
final JTree tree, final Object value, boolean isSelected,
boolean expanded, boolean leaf, int row) {
this.tree = tree;
treeModel = (DefaultTreeModel) tree.getModel();
node = (DefaultMutableTreeNode) value;
Object userObject = node.getUserObject();
this.str = (String) userObject;

TreeNode[] nodes = treeModel.getPathToRoot(node);
final TreePath path = new TreePath(nodes);

editorComponent = (TreeComponent) rend.getTreeCellRendererComponent(
tree, value, isSelected, expanded, leaf, row, false);
editorComponent.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
TreeEditor.this.stopCellEditing();
int x = e.getX();
if (x >= 0 && x <= 16) {
System.out.println(
"you clicked the image for row " + str);
} else if (x > 16) {
System.out.println(
"you clicked the text for row " + str);
tree.setSelectionPath(path);
}
}
});
return editorComponent;
}

@Override
public boolean isCellEditable(EventObject anEvent) {
return true;
}

@Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}

@Override
public boolean stopCellEditing() {
tree.cancelEditing();
return false;
}

@Override
public Object getCellEditorValue() {
return null;
}

@Override
public void cancelCellEditing() {
}

@Override
public void addCellEditorListener(CellEditorListener l) {
}

@Override
public void removeCellEditorListener(CellEditorListener l) {
}
}
}

最佳答案

如何实现复杂单元格编辑器的快速概述。假设编辑器的所有交互元素确实编辑了节点的 userObject 的属性 - 就像 OP 的完整代码中的情况一样。

合作者

  • 具有多个属性的模拟数据对象
  • 具有多个子级的渲染器,每个子级都绑定(bind)到数据对象的一个​​属性
  • 使用渲染组件的“实时”实例的编辑器,即根据需要添加监听器以遵守编辑器的契约(Contract)

一些代码(显然可用于实际使用,只是为了了解想法:)

public static class ViewProvider extends AbstractCellEditor 
implements TreeCellEditor, TreeCellRenderer {

private JCheckBox firstBox;
private JButton colorButton;
private JComponent nodePanel;
private JButton nameButton;

private Data data;
private boolean ignore;

public ViewProvider(boolean asEditor) {
initComponents();
if (asEditor)
installListeners();
}

protected void initComponents() {
nodePanel = new JPanel();
nodePanel.setOpaque(false);
firstBox = new JCheckBox();
colorButton = new JButton();
// if we need something clickable use something ... clickable :-)
nameButton = new JButton();
nameButton.setContentAreaFilled(false);
nameButton.setOpaque(true);
nameButton.setBorderPainted(false);
nameButton.setMargin(new Insets(0, 0, 0, 0));
nodePanel.add(firstBox);
nodePanel.add(colorButton);
nodePanel.add(nameButton);
}

protected void installListeners() {
ActionListener cancel = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
cancelCellEditing();
}

};
nameButton.addActionListener(cancel);
ActionListener stop = new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
stopCellEditing();
}

};
firstBox.addActionListener(stop);
// Note: code for using a button to trigger opening a dialog
// is in the tutorial, should replace this
colorButton.addActionListener(stop);
}

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
Data data = (Data) ((DefaultMutableTreeNode) value).getUserObject();
firstBox.setSelected(data.isVisible);
colorButton.setBackground(data.color);
nameButton.setText(data.name);
nameButton.setBackground(selected ? Color.YELLOW : tree.getBackground());
nameButton.setFont(tree.getFont());
return nodePanel;
}

@Override
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row) {
// copy to not fiddle with the original
data = new Data((Data) ((DefaultMutableTreeNode) value).getUserObject());
ignore = true;
getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, false);
ignore = false;
return nodePanel;
}

@Override
public Object getCellEditorValue() {
return data;
}

@Override
public boolean shouldSelectCell(EventObject anEvent) {
// at this point the editing component is added to the tree
// and the mouse coordinates still in tree coordinates
if (anEvent instanceof MouseEvent) {
MouseEvent me = (MouseEvent) anEvent;
Point loc = SwingUtilities.convertPoint(me.getComponent(),
me.getPoint(), nodePanel);
return loc.x >= nameButton.getX();
}
return false;
}

@Override
public boolean stopCellEditing() {
if (ignore) return false;
// real-world data will have setters
data.isVisible = firstBox.isSelected();
return super.stopCellEditing();
}

@Override
public void cancelCellEditing() {
if (ignore) return;
data = null;
super.cancelCellEditing();
}

}

// simple Data - obviously not for production
public static class Data {
boolean isVisible;
Color color;
String name;

public Data(boolean isVisible, Color color,
String name) {
this.isVisible = isVisible;
this.color = color;
this.name = name;
}

/**
* A copy constructor to allow editors to manipulate its
* properties without changing the original.
*
* @param original
*/
public Data(Data original) {
this.isVisible = original.isVisible;
this.color = original.color;
this.name = original.name;
}
}

// usage:
DefaultMutableTreeNode root = new DefaultMutableTreeNode(
new Data(true, Color.RED, "someName"));
root.add(new DefaultMutableTreeNode(new Data(true, Color.GREEN, "other")));
root.add(new DefaultMutableTreeNode(new Data(false, Color.BLUE, "whatagain")));
root.add(new DefaultMutableTreeNode(new Data(false, Color.YELLOW, "dummy")));

JTree tree = new JTree(root);
tree.setCellRenderer(new ViewProvider(false));
tree.setCellEditor(new ViewProvider(true));
tree.setEditable(true);

关于java - JTree 单元格编辑器接收鼠标点击的方式因操作系统而异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734033/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com