无法在Java Swing中更新JButton
我试图在Java中构建一个TicTacToe游戏,并使用Swing进行GUI。因为我不太了解Swing,所以我使用JButton来创建平铺。最初,所有的瓷砖都是空白的。 现在,当用户单击一个空磁贴,即一个空按钮时,我想在该按钮上放置一个描绘图像的“X”或“O”。但我不能这么做。感谢您的帮助。我已经试过了,但没用 这是我的密码:无法在Java Swing中更新JButton,java,swing,jbutton,repaint,actionevent,Java,Swing,Jbutton,Repaint,Actionevent,我试图在Java中构建一个TicTacToe游戏,并使用Swing进行GUI。因为我不太了解Swing,所以我使用JButton来创建平铺。最初,所有的瓷砖都是空白的。 现在,当用户单击一个空磁贴,即一个空按钮时,我想在该按钮上放置一个描绘图像的“X”或“O”。但我不能这么做。感谢您的帮助。我已经试过了,但没用 这是我的密码: /* Showing only required code */ public void run(){ /* Creating blank JButt
/* Showing only required code */
public void run(){
/* Creating blank JButtons */
for (int i = 0; i < 3; i++) {
for(int j = 0; j<3; j++){
tile[i][j] = new JButton("");
tile[i][j].setActionCommand("Tile: (" + String.valueOf(i) + "," + String.valueOf(i) + ")");
/* tile[i][j] has setActionCommand as "Tile: (i,j)" */
panel.add(tile[i][j]);
}
}
panel.setBounds(140, 170, 300, 300);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/* HERE LIES THE MAIN PROBLEM AS BUTTONS ARE NOT UPDATED AS EXPECTED*/
public void actionPerformed(ActionEvent e) {
// when lefttop corner tile is clicked
if("Tile: (0,0)".equals(e.getActionCommand())){
if(tileDone[0][0] == false){ // checking if its still empty
if(currentPlayer.equals("X")){ // checking if current player is "X"
tile[0][0] = new JButton(new ImageIcon("/home/kaustubh/Desktop /java/TicTacToe/X.png"));
panel.add(tile[0][0]);
panel.repaint();
this.repaint();
System.err.println();
}
else{
tile[0][0] = new JButton(new ImageIcon("/home/kaustubh/Desktop/java/TicTacToe/O.png"));
panel.add(tile[0][0]);
panel.repaint();
this.repaint();
System.err.println();
}
tileDone[0][0] = false;
}
}
}
/*仅显示所需代码*/
公开募捐{
/*创建空白jbutton*/
对于(int i=0;i<3;i++){
对于(int j=0;j不清楚为什么要在actionPerformed()
中再次添加按钮。如果计划再次添加按钮,首先需要删除旧按钮。相反,您可能只是想更新图标
public void actionPerformed(ActionEvent e) {
// when lefttop corner tile is clicked
if("Tile: (0,0)".equals(e.getActionCommand())){
if(tileDone[0][0] == false){ // checking if its still empty
if(currentPlayer.equals("X")){ // checking if current player is "X"
// here...
tile[0][0].setIcon(new ImageIcon("/home/kaustubh/Desktop /java/TicTacToe/X.png"));
//panel.add(tile[0][0]); // remove this
panel.repaint();
this.repaint();
System.err.println();
}