2015-10-29 109 views
1

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

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)); 

回答

0

这是最好的办法我看我适合去这个问题。将你的JButtons加载到数组或ArrayList中。然后在他们的动作中,监听器让他们通过索引从数组或数组列表中选择一个jbutton,其中您可以使用Math.random()方法来执行此操作。这会产生一个随机数。确保他们的静态,以便你可以操纵他们从其他类。