gpt4 book ai didi

java - 从 popmenu 操作事件中获取右键单击位置

转载 作者:搜寻专家 更新时间:2023-10-31 19:47:46 25 4
gpt4 key购买 nike

我有一个 java 程序,当在 JPanel 中右键单击时,它会打开一个弹出菜单。单击任何弹出菜单项时,我想打印在终端中触发弹出菜单的右键单击的位置。我该怎么做呢?如何从弹出操作事件中获取发生右键单击的位置?

如果弹出菜单位于 JComponent 中,代码如何更改?

这是程序。

    import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;

public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(300, 200);

Action cutAction = new TestAction("Cut");
Action copyAction = new TestAction("Copy");
Action pasteAction = new TestAction("Paste");

JPopupMenu popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);

JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);

panel.addMouseListener(new MouseAdapter() {});
}

class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}

public void actionPerformed(ActionEvent event)
{
System.out.println("Right click happened at ?"); // How do I get right click location?
}
}
}

最佳答案

为按下事件添加一个鼠标监听器,(点击事件被弹出窗口捕获):

    panel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
clickLocation.setSize(e.getX(), e.getY());
}
});
Action cutAction = new TestAction("Cut", clickLocation);
Action copyAction = new TestAction("Copy", clickLocation);
Action pasteAction = new TestAction("Paste", clickLocation);

打印尺寸:

    private Dimension clickLocation;

public TestAction(String name, Dimension clickLocation) {
super(name);
this.clickLocation = clickLocation;
}

public void actionPerformed(ActionEvent event) {
System.out.println("Right click happened at " + clickLocation);
}

关于java - 从 popmenu 操作事件中获取右键单击位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13660804/

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