[英]Unable to update JButton in Java Swing
I am trying to build a TicTacToe game in Java and using Swing for GUI. 我正在尝试用Java构建一个TicTacToe游戏 ,并将Swing用于GUI。 As I doesn't know much Swing, I am using JButton for creating tiles.
因为我不太了解Swing,所以我正在使用JButton创建图块。 Initially all the tiles are blank.
最初,所有磁贴都是空白的。 Now, when a user clicks on an empty tile ie an empty button, I want to put a "X" or "O" depicting image on that button.
现在,当用户单击空白图块(即空白按钮)时,我想在该按钮上放置一个描绘图像的“ X”或“ O” 。 But I'm unable to do that.
但是我做不到。 Any help is appreciated.
任何帮助表示赞赏。 I already tried things, but not working.
我已经尝试过了,但是没有用。
Here is my code: 这是我的代码:
/* 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;
}
}
}
} }
It's unclear why you are adding the button again in actionPerformed()
. 目前尚不清楚为什么要在
actionPerformed()
再次添加按钮。 If you plan to add the button again, you first need to remove the old one. 如果您打算再次添加按钮,则首先需要删除旧按钮。 Instead, you probably mean to just update the icon.
相反,您可能只想更新图标。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.