因为我改变了字符串,但它保持在jlable中。 我想从特定的时间段更新该字符串
答案 0 :(得分:1)
尝试使用SwingUtilities.invokeLater或invokeAndWait。
如下面的代码所示。
希望它有所帮助。
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LabelUpdater {
public static void main(String[] args) {
LabelUpdater me = new LabelUpdater();
me.process();
}
private JLabel label;
private void process() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setContentPane(new JPanel(new BorderLayout()));
label = new JLabel(createLabelString(5));
frame.getContentPane().add(label);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
snooze();
for (int i = 5; i >= 1; i--) {
final int time = i - 1;
snooze();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText(createLabelString(time));
}
});
}
}
private void snooze() {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private String createLabelString(int nbSeconds) {
return "Still " + nbSeconds + " seconds to wait";
}
}
答案 1 :(得分:1)
使用javax.swing.Timer(tutorial)。这将通过在事件派发线程上执行来确保线程安全。
public class TimerDemo {
public static void main(String[] args) {
final int oneSecondDelay = 1000;
final JLabel label = new JLabel(Long.toString(System.currentTimeMillis()));
ActionListener task = new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
label.setText(Long.toString(System.currentTimeMillis()));
}
};
new javax.swing.Timer(oneSecondDelay, task).start();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(label);
frame.pack();
frame.setVisible(true);
}
}