我想要一个带有2个按钮(最终还有更多个按钮)的JFrame应用程序,我可以使用它们在多个重复动作之间进行切换,为简便起见,我现在仅使用控制台打印,尽管稍后可能会调用一个方法.这是JFrame的框架:
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();
}
}
}
但是当我单击一个按钮后,它一直停留在该打印件上,甚至无法再与这些按钮进行交互.我是否缺少某些东西,还是需要一个完全不同的结构?我已经检查了许多不同的程序,但是它们太复杂了,以至于我无法理解,阅读Swing中的并发并没有为我解决.
编辑:还没有“停止”命令,因为我现在不需要它.