2

我在为一组 JButton 着色时遇到问题。

我制作了两个 JButton 数组:

public JButton Speler1[] = new JButton[140]; //Player1
public JButton Speler2[] = new JButton[140]; //Player2

这两个按钮阵列构成了赛车游戏的通道 1 和通道 2。我希望玩家 1 和 2 的位置在两个屏幕上都有颜色。所以玩家 1 可以看到玩家 2 在哪里,反之亦然。

我已经制作了一种方法,可以将两个玩家的位置发送给彼此。

if (message.contains("Positie")) {
   String posit = message.replaceFirst("Positie", "");
   int positi = Integer.valueOf(posit);
   positie2 = positi;
   kleurHokje kleur = new kleurHokje();
   kleur.hokVerkleur(positi); // positi is the position of each player
}

因此,当我调用方法 hokVerkleur(positi) 时,我想更改通道 2 上的按钮。

class kleurHokje{
    public void hokVerkleur(int loc){
        Speler2[loc].setBackground(Color.yellow);
        Speler2[positie2].setBackground(Color.gray);                
    }
}

它只是行不通。虽然我对 Speler1[positie] 所做的几乎相同,但 Speler1 不使用网络,它可以按我的意愿工作。

任何帮助表示赞赏,

谢谢杰夫

编辑:如果我将我的代码放在其中一个 MouseListener 中,它可以正常工作,而是让它自动着色,而不必每次都单击。

 class Klaar extends MouseAdapter {

    public void mouseClicked(MouseEvent e) {            
        Speler2[positie2].setBackground(Color.gray);
    }
}

附言。我的母语不是英语,希望你能理解我的问题。

4

2 回答 2

4
If I place my code in one of the MouseListeners it works fine:

同意,如果您从 BackGroung Task 更改 JButton 的颜色,那么有任何更改,您在 Swing 中的 Concurency有一些问题,您更新到的 GUI 已超出 EDT,

1) 然后你必须将着色 JButtons 包装到 invokeLater();

    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            Speler2[loc].setBackground(Color.yellow);
            Speler2[positie2].setBackground(Color.gray);
        }
    });

2)但你必须使用常规的 Swing 方法来解决

2a) 将您的 GUI 相关代码包装到javax.swing.Action

2b) 初始化你的 BackGroung 任务

于 2011-10-05T18:00:47.987 回答
0

做了一个可运行的线程,作为一个魅力。谢谢大家的帮助。

public void actionThread() {
    Thread t = new Thread() {

        public void run() {
            while (!stop) {
                tegenspelerPositie();
                Score();
                eigenOgen();
                try {
                    sleep(100);
                } catch (InterruptedException ex) {
                }
            }
        }
    };
    t.start();
}
于 2011-10-06T14:05:13.730 回答