问题是,我有26个JButton
组件,我必须从中随机选择8个组件并将它们放在两个JPanel
组件中的2 x 2网格中。单击一个按钮时,我需要用从原件26中选择的另一个随机按钮替换它。我无法弄清楚如何更换用另一个随机按钮单击的按钮。到目前为止我所拥有的确实有效,但可能不是最好的方法(我显然是一个菜鸟)。
有人能为我提供一些见解或至少引导我走向正确的方向吗?
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JVowelConsonant extends JFrame implements ActionListener
{
int x = 0;
String[] letter = {"a", "e", "i", "o", "u", "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"};
JPanel panel1 = new JPanel(new GridLayout(2, 2));
JPanel panel2 = new JPanel(new GridLayout(2, 2));
JPanel panel3 = new JPanel(new FlowLayout());
JLabel label = new JLabel("");
JButton[] buttons = new JButton[26];
public JVowelConsonant()
{
super("Vowel or Consonant?");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for(x = 0; x < buttons.length; ++x)
{
buttons[x] = new JButton(letter[x]);
buttons[x].addActionListener(this);
}
setLayout(new FlowLayout());
add(panel1, FlowLayout.LEFT);
add(panel2, FlowLayout.CENTER);
add(panel3, FlowLayout.RIGHT);
ArrayList<Integer> list = new ArrayList<Integer>();
for(int y = 0; y < 26; ++y)
{
list.add(new Integer(y));
}
Collections.shuffle(list);
for(int y = 0; y <= 3; ++y)
{
panel1.add(buttons[list.get(y)]);
}
for(int y = 4; y <= 7; ++y)
{
panel2.add(buttons[list.get(y)]);
}
panel3.add(label);
setSize(500, 500);
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if(source == buttons[0] || source == buttons[1] || source == buttons[2] || source == buttons[3] || source == buttons[4])
{
String type = "Vowel";
label.setText(type);
}
else
{
String type = "Consonant";
label.setText(type);
}
}
public static void main(String[] args)
{
JVowelConsonant frame = new JVowelConsonant();
frame.setVisible(true);
}
}