我想做一个游戏,按钮会点亮,用户将不得不按下按钮在给定的时间。我的程序如何随机按下一个按钮?
目前,我的程序有12个按钮可以执行某些操作。我正在努力使这些按钮被程序随机调用。到目前为止,我只有12个按钮可以在用户按下时更改文本。
现在我需要一种方法让它们随机按下程序本身而不是用户。任何想法是如何在java中完成的?
// **** Panels for buttons ****
JPanel panelButtons = new JPanel(); // making the panel for the buttons
panelButtons.setLayout(new GridLayout(3, 4)); // setting the layout of the buttons to 3x4 as shown above
b1 = new JButton(" ⃝"); // creating button and setting its default text
b1.setFont(fontText); // setting the font
b1.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "1"); // sends the name of the user that pressed the button and which button
String field1 = b1.getText(); // gets the text from the button and stores it in a String
if(field1 == " ⃝"){ // checks if the string is equal to an empty circle
b1.setText("⬤"); // if true then change to a full circle
}
else if (field1 == "⬤"){ // opposite of the above if statement
b1.setText(" ⃝");
}
}
});
panelButtons.add(b1); // adding the button to the panel
b2 = new JButton(" ⃝"); // creating button and setting its default text
b2.setFont(fontText); // setting the font
b2.addActionListener(new ActionListener(){ // action listener to do something when pressed
public void actionPerformed(ActionEvent e) {
sendMessage(user + "2"); // sends the name of the user that pressed the button and which button
String field2 = b2.getText(); // gets the text from the button and stores it in a String
if(field2 == " ⃝"){ // checks if the string is equal to an empty circle
b2.setText("⬤"); // if true then change to a full circle
}
else if (field2 == "⬤"){ // opposite of the above if statement
b2.setText(" ⃝");
}
}
});
panelButtons.add(b2); // adding the button to the panel
从1到12生成一个随机数,进行大小写切换,然后根据大小写触发按钮执行的操作。 – 2015-03-25 10:45:22
@CeilingGecko坏主意。下周他需要14个按钮时会发生什么。还是8?每次数字改变时,你都必须更新switch语句。非常烦人和容易出错。 – GhostCat 2015-03-25 10:47:31
@EddyG您的观点有其优点,但要在现实世界的情况下公平,这种重大的设计变更不应该经常发生。 (除非有意)在可维护性和可读性之间应该做出妥协,在这种情况下,由于我们没有看到整体情况,因此可能很难确定从长远来看哪种选择会更好。 – 2015-03-25 10:55:23