gpt4 book ai didi

java - ActionEvent和MouseEvent右键单击JAVA Mac

转载 作者:行者123 更新时间:2023-11-30 09:11:06 24 4
gpt4 key购买 nike

我不确定这是 Mac 问题还是我的代码问题。我正在创建一个按钮网格。对于每个按钮,我使用 ActionEvent 进行常规单击,使用 MouseEvent 进行右键单击。当我按住 CTRL 键并单击鼠标事件时会发生什么情况,但该操作甚至会触发。有没有办法在同时使用 Action 和鼠标事件的同时解决这个问题?相关代码:

查看构造函数:

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
button[i][j] = new Cell();
button[i][j].addActionListener( new changeButtonHandler() );
button[i][j].addMouseListener( new handleRight() );
playArea.add(button[i][j]);

}
}

Action 事件类:

public class changeButtonHandler implements ActionListener
{
/**
* Action performed after button is clicked
*
*/
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e)
{

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (button[i][j] == e.getSource())
{
//do stuff
}
else if(button[i][j].mine==false){
//do other stuff
}
}

}
}
}
}//end changeButtonHandler class

鼠标事件类

public class handleRight implements MouseListener {

/**
* Action performed after button is right-clicked
*
*/
public void mouseClicked(MouseEvent e)
{
if (SwingUtilities.isRightMouseButton(e) || e.isControlDown()) {
System.out.println("Right Worked");
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
if (button[i][j] == e.getSource())
{
//do stuff
}
}
}
}
}

最佳答案

当我尝试用我自己的 minimal example program 重现您的问题时,我做不到。 MouseListener 按预期工作,ActionListener 按预期工作:

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

public class TestButtonRightClick {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JButton button = new JButton("Test Me!");
button.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("ActionListener invoked");
}
});
button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
System.out.println("Right Button Pressed");
}
}
});

JPanel panel = new JPanel();
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
});
}
}

编辑:为什么使用 SwingUtilities 而不是 e.getMouseButton()

// ? SwingUtilities
if (SwingUtilities.isRightMouseButton(e) || e.isControlDown()) {

请注意,如需进一步帮助,请考虑创建您自己的 minimal example program与我上面的类似。


编辑2

要检查按下按钮时 ctrl 键的状态,请检查 ActionListener 中 ActionEvent 的修饰符:

           @Override
public void actionPerformed(ActionEvent e) {
if ((e.getModifiers() & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK) {
System.out.println("control pressed");
} else {
System.out.println("ActionListener invoked");
}
}
});

关于java - ActionEvent和MouseEvent右键单击JAVA Mac,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22262017/

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