有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java MouseListener未触发

我已经在这段代码上工作了很长时间,并且来回地处理鼠标事件。我有一个MainClass(实现MouseListener)。UI有一个JFrame,它有一个basePanelBasePanelGridPanel(调用网格实现MouseListener)。GridGridLayout上有单独的JPanel。当我点击Grid时,它会触发Grid中的事件方法,但不会触发MainClass中的事件方法。它以前工作得更早,但现在不行了

在我输入的接口方法中,只是println来跟踪触发的内容

主类

public class PlayConnect implements MouseListener{

private JFrame mainFrame;
private JPanel basePanel,
buttonPanel,
messagePanel;

private Grid gridPanel;

private void startGame(){

    mainFrame = new JFrame("Connect-4");
    mainFrame.setSize(800, 700);    

    basePanel = new JPanel();
    basePanel.setName("basePanel");
    mainFrame.add(basePanel);

    gridPanel = new Grid();
    gridPanel.addMouseListener(this); //Added MouseListner
    gridPanel.setName("GridPanel");


    basePanel.add(gridPanel,BorderLayout.CENTER);

    messagePanel = new JPanel();
    //      messagePanel.addMouseListener(this);
    messagePanel.setName("messagePanel");

    messArea = new JTextArea();
    messArea.setEditable(false);
    messFont = new Font(Font.SERIF, Font.BOLD, 20);
    messArea.setFont(messFont);
    messArea.setText("Game On !");

    messagePanel.add(messArea);
    basePanel.add(messagePanel,BorderLayout.PAGE_END);


    buttonPanel = new JPanel();
    buttonPanel.setName("button Panel");
    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));


    randButton = new JButton("Random Moves");
    buttonPanel.add(randButton);
    randButtonHandle = new RandomMoves();
    randButton.addActionListener(randButtonHandle);
    basePanel.add(buttonPanel,BorderLayout.LINE_END);


    mainFrame.setVisible(true);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


}

Grid

public class Grid extends JPanel implements MouseListener {

private Cell[][] gridUI = new Cell[6][7];
private static int[][] gridTrack = new int[6][7];
private static int player = 1;
private static Boolean gameOver = false;
public Boolean randPlayer;
private static ArrayList<Cell> cellArray = new ArrayList<Cell>();

public Grid(){
    //      setPreferredSize(new Dimension(600,700));;
    setLayout(new GridLayout(6, 7));
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            Cell tempCell = new Cell(i,j);
            tempCell.addMouseListener(this);
            gridUI[i][j] = tempCell;
            gridTrack[i][j] = 0;
            add(tempCell);

            int index = i*6 + j;
            cellArray.add(tempCell);

        }

    }
    addMouseListener(this);
}

共 (1) 个答案

  1. # 1 楼答案

    这就是Swing中事件处理的工作原理。从一个非常高级的视图来看——当生成一个事件时,会检查该坐标处最顶层的组件,看它是否会使用该事件。如果是这样,事件将被传递到该组件并停止处理;如果没有,将检查该位置的下一个最顶层组件,依此类推,直到到达顶层容器。一个事件永远不会传递给多个组件

    如果确实需要顶级容器来获取所有事件,即使是在具有注册侦听器的子级上,也可以通过使用AWTEventListener或使用GlassPane并自行处理重新分派事件来实现,如answers to this question中所述