创建一个不断变化颜色的按钮面板

时间:2019-04-04 19:47:23

标签: java

我正在尝试用Java创建一个按钮面板,该面板每秒随机更改其颜色,直到按下按钮为止。我一直在尝试实现一个actionListener并使用javax.swing.timer,但是它不能将timer.start()识别为计时器类的函数。另外,我不断收到一条错误消息,指出我的类ChangeingButtons需要声明为抽象,或者需要在ActionListener中实现抽象方法'actionPerformed(ActionEvent)。我也不确定如何在按下后使其停止改变颜色。

public class ChangingButtons extends JFrame implements ActionListener {
    private static final int numButtons = 8; 
    private static JButton[] colorButtons;
    Timer timer;
    public ChangingButtons() { // creates the window
        newWindow(); //First creates grid
        setSize(400, 400);
        setVisible(true); // makes it appear
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void newWindow() {
        JPanel btnPanel = new JPanel();
        this.colorButtons= new JButton[numButtons];
        btnPanel.setLayout(new GridLayout(numButtons / 2, 2)); // 8 buttons total; 4 rows
        Random rand = new Random(); //to randomize colors shown
        for (int jj = 0; jj< numButtons; jj++) { //creates the buttons and adds it
            this.colorButtons[jj] = new JButton();
            this.colorButtons[jj].setBackground(new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
            this.colorButtons[jj].setOpaque(true); 
            this.colorButtons[jj].setBorderPainted(false);
            this.colorButtons[jj].addActionListener(this);
            btnPanel.add(this.colorButtons[jj]); 
        add(btnPanel);
    }

    public static void main(String[] args) { //initializes btngrid
        ChangingButtons newWindow = new ChangingButtons();

        ActionListener action = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Random rand = new Random();
                for (JButton otherBtn : colorButtons) { //for(type item : item)

                    otherBtn.setBackground(new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));

                }
            };

            Timer timer = new Timer(1000, action);
        timer.start();
        };
    }
}

0 个答案:

没有答案