简体   繁体   中英

JButton color won't change

I'm making a reaction time game where a button will turn green and you have to hit it as fast as possible, but the button will not change colors. Can someone tell me why this is happening? Also, how could I get my program to wait until a random time (method is below) and then change color? I tried using Thread.sleep but couldn't get it to function properly.

mport java.awt.Color;
import java.util.Random;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Game extends JFrame implements ActionListener {

    double start = System.nanoTime();
    double end;
    String startTime = String.valueOf(start);
    String endTime = String.valueOf(end);

    private JTextField displayTime = new JTextField(15);
    private JButton stopButton = new JButton("STOP");
    DecimalFormat deci = new DecimalFormat();
    Font f = new Font("ARIAL", Font.BOLD, 25);

    public Game() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        deci.setMaximumFractionDigits(4);
        deci.setMinimumFractionDigits(1);


        stopButton.addActionListener(this);
        stopButton.setPreferredSize(new Dimension(250, 250));
        stopButton.setFont(f);
        stopButton.setBackground(Color.red);

        add(displayTime);
        add(stopButton);

        pack();
        setVisible(true);

        waitRandom();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == stopButton) {
            end = System.nanoTime();
            double time = end - start;
            double seconds = time / Math.pow(10, 9);
            String finalTime = String.valueOf(deci.format(seconds));
            displayTime.setFont(f);
            displayTime.setAlignmentX(LEFT_ALIGNMENT);
            displayTime.setText(finalTime + " sec.");

        }
    }

    public void waitRandom() {

        Random random = new Random();
        int randomNumber = random.nextInt(10);
        int randomTime = randomNumber * 100;

        stopButton.setBackground(Color.green);
        stopButton.setOpaque(true);
        System.out.println(randomTime);

    }

}

The problem is, what "looks" like the buttons background, isn't. It's the buttons "content", if you add

    stopButton.setContentAreaFilled(false);

to your waitRandom method, you will see...

在此处输入图片说明

Doing all the UI setup in the constructor is dodgy and error-prone, but I'm going to guess that the real problem is that you're not allowing the UI to setup, render, and display on the event dispatch thread, then waiting on another thread, and then changing the color on the event dispatch thread. You don't give us the main() and you don't tell us what is actually happening, so it's hard to tell.

The solution to your immediate question is to add several lines of code to the end of your if block body in actionPerformed() :

            stopButton.setBackground(Color.red);
            paint(getGraphics());
            try {
                Thread.sleep(new Random().nextInt(10) * 100);
            } catch (InterruptedException x) {
                x.printStackTrace();
            }
            stopButton.setBackground(Color.green);

Now you can delete your waitRandom() method and its invocation from the constructor. Lastly, change the initial color, as set in the constructor, to green instead of red.

Note the Thread.sleep() call is a no-no here; you will want to use javax.swing.Timer instead. This is just to get you going in the right direction.

There's still plenty for you to figure out after this, but hopefully it sets you up.

I think the problem is in this: e.getSource() == stopButton . You should use .equals()

Try this bro :)

buttonName.setUI((ButtonUI) BasicButtonUI.createUI(buttonName));
buttonName.setBackground(Color.CYAN);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM