[英]how to force java swing gui to update on this snippet
從下面的最小工作示例中,我想要的是在單擊單選按鈕后的很小的時間間隔內兩次更改其單選按鈕的文本。 即,當我單擊按鈕時,我想立即將其文本更改為“ 1”,並在3秒后再次將其文本更改為“ 2”。
public class Example extends javax.swing.JFrame {
public Example() {
jRadioButton1 = new javax.swing.JRadioButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jRadioButton1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton1ItemStateChanged(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGap(137, 137, 137)
.addComponent(jRadioButton1).addContainerGap(242, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addGap(126, 126, 126)
.addComponent(jRadioButton1).addContainerGap(153, Short.MAX_VALUE))
);
pack();
}
private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton1.setText("1");
//repaint();
try { Thread.sleep(3000); }
catch (InterruptedException e) {}
jRadioButton1.setText("2");
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Example().setVisible(true);
}
});
}
private javax.swing.JRadioButton jRadioButton1;
}
以上顯然不起作用。
我知道我應該以某種方式使用repaint()或SwingUtilities.invokeLater()或一個新線程,但是我還無法通過它們的任何組合來達到預期的效果。
我該怎么辦?
提前致謝。
首先,改變這個
private javax.swing.JRadioButton jRadioButton1;
至
public javax.swing.JRadioButton jRadioButton1;
然后。 你可以寫這節課
public class Updater extends Thread {
private Example e ;
public Updater(Example e) {
this.e = e;
}
public void run(){
try {
Thread.sleep(3000);
e.jRadioButton1.setText("2");
} catch (InterruptedException ex){
}
}
}
現在在這里用這種方法。
private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton1.setText("1");
new Updater(this).start();
}
休眠在事件分發線程中會阻止它,並防止您發現時發生繪圖。 它還使UI的其余部分暫時無響應,因此它在您不應該做的事情列表中。
在擺動應用程序中運行延遲或重復動作的標准方法是使用擺動計時器 。 它可以在事件分發線程中正確運行操作,因此您也無需特別注意線程安全性。 使用Timer
您的按鈕動作將變為:
private void jRadioButton1ItemStateChanged(java.awt.event.ItemEvent evt) {
jRadioButton1.setText("1");
Timer timer = new Timer(3000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jRadioButton1.setText("2");
}
});
timer.setRepeats(false);
timer.start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.