Random 如何设置随机按钮的颜色?
我正在尝试用java制作一个简单的游戏。基本上,单击一个“开始”按钮后,其他3个按钮(标记为a、B和C)将在单独的JFrame中弹出。我希望在第二个JFrame打开时,其中一个按钮(随机按钮)立即变为红色。每次单击“开始”按钮时,随机按钮必须为红色。除此之外,单击红色按钮后,我希望另一个随机按钮为红色,循环继续。以下是我目前的代码:Random 如何设置随机按钮的颜色?,random,colors,jbutton,Random,Colors,Jbutton,我正在尝试用java制作一个简单的游戏。基本上,单击一个“开始”按钮后,其他3个按钮(标记为a、B和C)将在单独的JFrame中弹出。我希望在第二个JFrame打开时,其中一个按钮(随机按钮)立即变为红色。每次单击“开始”按钮时,随机按钮必须为红色。除此之外,单击红色按钮后,我希望另一个随机按钮为红色,循环继续。以下是我目前的代码: import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.eve
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());
}
}
这是我认为最合适的方式。将JButtons加载到数组或arraylist中。然后,在他们的操作中,侦听器让他们通过索引从数组或数组列表中选择一个jbutton,您可以使用Math.random()方法来执行此操作。这会产生一个随机数。确保它们也是静态的,以便可以从另一个类中操纵它们 这是我认为最合适的方式。将JButtons加载到数组或arraylist中。然后,在他们的操作中,侦听器让他们通过索引从数组或数组列表中选择一个jbutton,您可以使用Math.random()方法来执行此操作。这会产生一个随机数。确保它们也是静态的,以便可以从另一个类中操纵它们
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));