Change JButton Color in a Thread

前端 未结 2 1900
深忆病人
深忆病人 2021-01-28 05:29

I am trying to make a game like simon: http://www.freegames.ws/games/kidsgames/simon/simon.htm#

I am making a smaller scale with only 2 buttons. I want the color to swit

2条回答
  •  误落风尘
    2021-01-28 06:33

    if(switchColor = true){
        button1.setBackground(Color.blue);
        button2.setBackground(Color.green);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        refresh();
        switchColor = false;
    } else {
        button1.setBackground(Color.green);
        button2.setBackground(Color.blue);
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        refresh();
    
        switchColor = true;
        }
    }
    

    In the above code change the following to

    if(switchColor = true){
    

    to

    if(switchColor == true){ 
    

    or just

    if(switchColor){
    

    And it is best to have your Runnable anonymous class inside

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
    
        }
    });
    

    than using a new Thread object to create and start the thread as it will be changing the Swing UI properties.

提交回复
热议问题