rollDice.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//generate roll
int roll = dice.getRoll();
addGameFeedMessage(players[1].getName() + " rolled " + roll);
//store the player's position before the roll
int currentPlayerPos = players[1].getPosition();
//update player's position
players[1].movePlayer(roll);
//move the player icon to the player's position
tiles[players[1].getPosition()].addIconCurrentPlayersPanel(players[1].getPlayerIcon());
//revalidate components
//tiles[currentPlayerPos].getCurrentPlayersPanel().revalidate();
//tiles[players[1].getPosition()].getCurrentPlayersPanel().revalidate();
//this loop was put in to see if doing revalidate() on all panels would make a difference but the problem is still there
for(int i = 0; i < tiles.length; i++)
{
tiles[i].getCurrentPlayersPanel().revalidate();
}
}
});
任何人都可以解释为什么掷骰子的 actionListener 中的 for 循环似乎不起作用,但它上面的 for 循环却完全相同?没有实际的错误,它只是不执行任何操作,但是它确实进入了 actionListener 并在我们将打印语句等放入其中时执行。
猜测 actionListeners 有点奇怪,但我不确定是什么。
如有任何帮助,我们将不胜感激,谢谢。
最佳答案
您应该调用validate()
在for循环
之后如下:
for(int i = 0; i < getNumOfPlayers(); i++)
{
currentPlayersOnTile[5].add(players[i].getPlayerIcon());
}
validate();
例如,考虑下面给出的代码:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class DemoPanels extends JFrame
{
public void createAndShowGUI()
{
final JPanel panel = new JPanel();
getContentPane().add(panel);
JButton button = new JButton("Click");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
for (int i = 0 ; i < 10 ; i++ )
{
JPanel panel1 = new JPanel();
panel1.add(new JButton(String.valueOf(i)));
panel.add(panel1);
}
validate();//comment this line and then compile and execute the code to see the effect
}
});
getContentPane().add(button,BorderLayout.SOUTH);
setVisible(true);
setSize(300,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
DemoPanels dp = new DemoPanels();
dp.createAndShowGUI();
}
});
}
}
注意:注释掉validate()
代码,然后编译执行看看效果。
关于java - Jbutton 事件处理程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15795209/