不知道标题是否可以理解。 不管怎样,我有一些 JMenuItems,并且我已经为这些设置了 mouseListener。
mntmExtractPaleographyFeature.addMouseListener(this);
其中mntmExtractPaleographyFeature是一个JMenuitem,this是实现MouseListener的类。
所以我为 mouseListener 添加了方法,例如
@Override
public void mouseReleased(MouseEvent arg0) {
if(arg0.getSource()==mntmExtractPaleographyFeature) {
//Code Here
}
现在我有了这个 JButton extractPaleographyB,它的功能与 JMenuItem 完全相同。我不想复制/粘贴代码两次(也因为它不是唯一的按钮/jmenuitem)。我尝试过
extractPaleographyB.addMouseListener(mntmExtractPaleographyFeature.getMouseListeners()[1]);
但它不起作用。有什么想法吗?
最佳答案
创建 Action并用于菜单项和按钮
教程中的一段代码
Action leftAction = new LeftAction(); //LeftAction code is shown later
...
button = new JButton(leftAction)
...
menuItem = new JMenuItem(leftAction);
要创建 Action 对象,通常创建 AbstractAction 的子类,然后实例化它。在您的子类中,您必须实现 actionPerformed 方法,以便在操作事件发生时做出适当的 react 。下面是创建和实例化 AbstractAction 子类的示例:
leftAction = new LeftAction("Go left", anIcon,
"This is the left button.",
new Integer(KeyEvent.VK_L));
...
class LeftAction extends AbstractAction {
public LeftAction(String text, ImageIcon icon,
String desc, Integer mnemonic) {
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
displayResult("Action for first button/menu item", e);
}
}
关于java - 在 JButton 上模拟 JMenuItem MouseListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31036360/