1
我想製作一個具有兩個(或多個)按鈕的搖擺應用程序,它們可以在正在進行的動作之間切換。爲了簡單起見,這些操作可能只是重複的打印。 下面是對JFrame框架:使用GUI的Java搖擺開關流程
public class DayNight extends JFrame implements ActionListener{
//JFrame entities
private JPanel animationPanel;
private JButton button;
private JButton button2;
public static void main(String[] args) {
DayNight frame = new DayNight();
frame.setSize(2000, 1300);
frame.setLocation(1000,350);
frame.createGUI();
frame.setVisible(true);
frame.setTitle("Day/Night Cycle, Rogier");
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
animationPanel = new JPanel();
animationPanel.setPreferredSize(new Dimension(2000, 900));
animationPanel.setBackground(Color.black);
window.add(animationPanel);
button = new JButton("choice1");
button.setFont(new Font("Arial", Font.PLAIN, 50));
window.add(button);
button.setActionCommand("choice1");
button.addActionListener(this);
button2 = new JButton("choice2");
button2.setFont(new Font("Arial", Font.PLAIN, 50));
window.add(button2);
button2.setActionCommand("choice2");
button2.addActionListener(this);
}
}
我試過以下,但現在我知道,這是一個完全錯誤的做法。
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
while ("Stop"!=(command)){
command = event.getActionCommand();
try{
Thread.sleep(500);
if ("choice1".equals(command)){
System.out.println("choice1");
}
else if("choice2".equals(command)){
System.out.println("choice2");
}
else{
System.out.println("no choice");
}
}
catch(InterruptedException ex){
Thread.currentThread().interrupt();
}
}
}
我已經閱讀了許多帖子和Java教程中的「併發性」文檔。我現在明白Idid錯了,但我仍然不知道如何開始。 我的(子)目標是讓程序繼續打印「choice1」(或任何其他動作),並在我按下另一個按鈕後切換到打印「choice2」。 有人能給我一點點正確的方向嗎?
退出重新發布的問題。將所有信息保存在一個線程中,以便每個人都知道已經建議的內容。 – camickr
我重新評估了我在這裏和reddit上得到的答案。我不能繼續我的老問題,因爲那時人們會生氣並告訴我「提出一個新問題」。他們然後告訴我不要發表一個新問題。之前發生過,只是跳過一步。 – RnRoger
'他們然後告訴我不要發佈新問題 - 這不是一個新問題。這就是爲什麼所有信息都應該出現在同一個問題中。這裏的答案(使用單獨的線程)與上一個問題中的答案相同,因爲問題是相同的。 – camickr