public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
JButton src = (JButton) event.getSource(); //get which button is clicked
if(src.equals(GO)) //if GO button is clicked
{
try {
runHack();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(src.equals(STOP)) //if STOP button is clicked
{
//do nothing
FeedBack.setText(null);
FeedBack.setText("Stopped");
}
}
我有一个程序,当您单击按钮GO
时,它将执行一个名为runHack();
的方法
private void runHack() throws AWTException
{
FeedBack.setText(null);
FeedBack.setText("Running(This doesn't print out)");
while(true)//infinite loop
{
FeedBack.setText("This doesn't print out");
}
}
runHack()
是运行无限循环的方法。当我单击 GO 按钮时,程序在执行 runHack()
方法时卡住。 “Running”
字符串未显示在 JLabel FeedBack
上。
我的问题是当程序处于无限循环时如何使事件仍然可用?我希望这样当我按下“停止”按钮时,程序就会退出无限循环。另外,我希望 JLabel FeedBack
在循环内工作。
最佳答案
您需要在新线程内运行这个无限循环。这是使用计时器的方法。swing计时器在单独的线程中运行。将延迟设置为零。因此它充当 while(true) 循环。
在您的代码中,由于长期任务(无限循环),您正在阻止 EDT
。您对文本字段所做的更改不会得到更新,因为 EDT
被阻止。
你需要 Swing 计时器
而不是java.util.Timer
import import javax.swing.Timer;
声明定时器
Timer t;//global declaration;
初始化//
t=new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FeedBack.setText("This doesn't print out");
}
});
当按钮点击时//
JButton src = (JButton) event.getSource(); //get which button is clicked
if(src.equals(GO)) //if GO button is clicked
{
try {
t.start();
} catch (AWTException e) {
e.printStackTrace();
}
}
if(src.equals(STOP)) //if STOP button is clicked
{
//do nothing
t.stop();
FeedBack.setText(null);
FeedBack.setText("Stopped");
}
正在更新...
一个完整的例子
import java.awt.AWTException;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.Timer;
public class example extends JFrame implements ActionListener{
Timer t;
private final JTextField FeedBack;
private JButton go;
private JButton stop;
int i=0;
public example() {
FeedBack=new JTextField("initial text");
go=new JButton("go");
stop=new JButton("stop");
go.addActionListener(this);
stop.addActionListener(this);
this.setLayout(new GridLayout(1, 3));
this.add(go);
this.add(stop);
this.add(FeedBack);
this.setVisible(true);
t = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FeedBack.setText(i+"");
i++;
}
});
}
public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();
System.out.println(src);
if (src==go) //if GO button is clicked
{
t.start();
}
if (src==stop) //if STOP button is clicked
{
//stop timer
t.stop();
//FeedBack.setText(null);
FeedBack.setText("Stopped");
}
}
public static void main(String[] args) {
example f = new example();
}
}
输出>>
关于java - 在无限循环中执行事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26568974/