GUIではJTree
、の左側に1つ表示していJPanel
ます。それぞれについて、マウスの右クリックで、右に統計を表示するように求めるメニューをNode(leaf)
表示したいと思います。JPopup
Node
JPanel
私はswingが初めてなので、コードを手伝ってくれる人はいますか。前もって感謝します。
よろしく、Tushar Dodia。
GUIではJTree
、の左側に1つ表示していJPanel
ます。それぞれについて、マウスの右クリックで、右に統計を表示するように求めるメニューをNode(leaf)
表示したいと思います。JPopup
Node
JPanel
私はswingが初めてなので、コードを手伝ってくれる人はいますか。前もって感謝します。
よろしく、Tushar Dodia。
ちょっとした混乱を引き起こしたようです (自分自身を混乱させます ;-) - ここに、componentPopup のターゲット ロケーション関連の構成を行うためのコード スニペットを示します。
JPopupMenu popup = new JPopupMenu();
final Action action = new AbstractAction("empty") {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
popup.add(action);
JTree tree = new JTree() {
/**
* @inherited <p>
*/
@Override
public Point getPopupLocation(MouseEvent e) {
if (e != null) {
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
action.putValue(Action.NAME, String.valueOf(path.getLastPathComponent()));
return e.getPoint();
}
action.putValue(Action.NAME, "no mouse");
return null;
}
};
tree.setComponentPopupMenu(popup);
JTree のメソッドを使用する
public TreePath getPathForLocation(int x, int y)
次に TreePath
public Object getLastPathComponent()
これにより、ユーザーが右クリックしたポイントから目的のノードが返されます。
@kleopatra ソリューションを使用して、少し変更しました。たぶんそれは最善の方法ではありませんが、私にとってはうまくいきます。
JTree tree = new JTree() {
private static final long serialVersionUID = 1L;
@Override public Point getPopupLocation(MouseEvent e) {
if (e == null) return new Point(0,0);
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
Object selected = path != null ? path.getLastPathComponent() : null;
setComponentPopupMenu(getMenuForTreeNode(getComponentPopupMenu(), selected));
setSelectionPath(path);
return e.getPoint();
}
};
public JPopupMenu getMenuForTreeNode(JPopupMenu menu, Object treeNode) {
if (menu == null) menu = new JPopupMenu("Menu:");
menu.removeAll();
if (treeNode instanceof MyTreeItem) {
menu.add(new JMenuItem("This is my tree item: " + treeNode.toString()));
}
return menu;
}