我已经在这段代码上工作了很长时间,并且不断地使用鼠标事件。我有一个MainClass (实现MouseListener)。UI有一个带有basePanel的JFrame。BasePanel有GridPanel (调用网格实现了MouseListener)。Grid在GridLayout上有单独的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);
}发布于 2015-05-13 04:34:25
这就是Swing中事件处理的工作方式。从一个非常高级的视图-当一个事件被生成时,在该坐标的最上面的组件被检查,以查看它是否将使用该事件。如果是,则将事件传递到该组件并停止处理;如果不是,则检查该位置的下一个最上面的组件,依此类推,直到到达顶级容器。一个事件永远不会被传递给多个组件。
如果您确实需要您的顶级容器来获取所有事件,即使是在具有注册侦听器的子级上,您也可以通过使用AWTEventListener或通过使用GlassPane并自己处理重新分派事件来实现,这两种方法都如answers to this question中所述。
https://stackoverflow.com/questions/30199007
复制相似问题