0
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 有点奇怪,但我不确定是什么。

任何帮助将不胜感激,谢谢。

4

1 回答 1

1

您应该validate()for loop以下方式调用:

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()然后编译执行看看效果。

于 2013-04-03T21:55:02.233 回答