如何设置随机JButton的颜色?

时间:2015-10-29 23:37:06

标签: random colors jbutton

我正在尝试用java制作一个简单的游戏。基本上,点击“开始”JButton后,其他3个按钮(标记为A,B和C)将弹出一个单独的JFrame。我希望其中一个按钮(随机按钮)在第二个JFrame打开时变为红色。每次单击开始按钮时,随机按钮必须为红色。除此之外,在我点击红色按钮后,我想要另一个随机按钮为红色,然后循环继续。到目前为止,这是我的代码:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Driver {
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Game());
    JFrame window;
    window = new JFrame("Clicking Game");
    window.setSize(300, 300);
    JButton b = new JButton("START");
    window.setLayout(new GridLayout(5,5));
    window.add(new JLabel("INSTRUCTIONS: \n Click the 'START' button to start the game."
            + " Click as many of the red buttons as you can before time runs out!"));
    window.add(b);
    window.pack();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
    b.addActionListener(new StartButtonHandler());
    b.addActionListener(new ActualButtonHandlers());



}

}

package code;


import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

class StartButtonHandler implements ActionListener {
        public void actionPerformed(ActionEvent e){
            JFrame win = new JFrame("CLICK FAST!");
            win.setVisible(true);
            win.setSize(500, 500);
            JButton a = new JButton("A");
            JButton b = new JButton("B");
            JButton c = new JButton("C");
            win.add(a);
            win.add(b);
            win.add(c);
            win.pack();
            win.setLayout(new GridLayout(1,3));

1 个答案:

答案 0 :(得分:0)

这是我认为最合适的方式。将JButtons加载到数组或arraylist中。然后在他们的动作中,侦听器让他们通过索引从数组或数组列表中选择一个jbutton,其中您可以使用Math.random()方法来执行此操作。这会生成一个随机数。确保它们的静态,以便您可以从其他类操作它们。