我想做一個遊戲,按鈕會點亮,用戶將不得不按下按鈕在給定的時間。我的程序如何隨機按下一個按鈕?
目前,我的程序有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