0
所以這是我下面的代碼:MouseListener的故障排除
package myProjects;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.*;
public class SecondTickTacToe extends JFrame{
public JPanel mainPanel;
public static JPanel[][] panel = new JPanel[3][3];
public static void main(String[] args) {
new SecondTickTacToe();
}
public SecondTickTacToe(){
this.setSize(300, 400);
this.setTitle("Tic Tac Toe");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainPanel = new JPanel();
for(int column=0; column<3; column++){
for(int row=0; row<3; row++){
panel[column][row] = new JPanel();
panel[column][row].addMouseListener(new Mouse());
panel[column][row].setPreferredSize(new Dimension(85, 85));
panel[column][row].setBackground(Color.GREEN);
addItem(panel[column][row], column, row);
}
}
this.add(mainPanel);
this.setVisible(true);
}
private void addItem(JComponent c, int x, int y){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 100.0;
gbc.weighty = 100.0;
gbc.fill = GridBagConstraints.NONE;
mainPanel.add(c, gbc);
}
}
class Mouse extends MouseAdapter{
public void mousePressed(MouseEvent e){
(JPanel)e.getSource().setBackground(Color.BLUE);
}
}
,但我得到就行
(JPanel)e.getSource().setBackground(Color.BLUE);
錯誤,我不知道爲什麼?我試圖檢索使用getSource()單擊了哪個面板,但它似乎不起作用。有沒有人有辦法解決嗎?謝謝。
哇......我不能相信我沒有意識到這一點。但是,嘿,現在我知道不這樣做!謝謝。 (一旦冷卻結束,我會將你的答案標記爲已解決) –