我尝试在JFrame表单中设置文本字段两次,但我设置的最后一个文本字段仍然存在。除了JFrame Form,我可以成功设置更多次。例如
class test extends JFrame {
public static void main(String[] args) {
test t = new test();
textfield.setText("Hello");
long a = System.currentTimeMillis();
long c = a;
while (c > a - 1000) {
a = System.currentTimeMillis();
}
textfield.setText("Hello2");
}
static private JTextField textfield;
public test() {
super();
setSize(300, 300);
textfield = new JTextField("Hello1");
add(textfield);
setVisible(true);
}}
上面的代码成功运行。首先展示"您好"然后" Hello2"一秒钟后但是在JFrame表单中,只显示" Hello2"而不是"你好"。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("Hello");
long a = System.currentTimeMillis();
long c = a;
while (c > a - 1000) {
a = System.currentTimeMillis();
}
jTextField1.setText("Hello2");
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(deneme.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new deneme().setVisible(true);
}
});
}
我还搜索了repaint()
,validate()
和revalidate()
方法。但由于我的项目是JFrame Form,因此没有JFrame对象。因此,我不能使用这些方法。
提前感谢您的回答。
答案 0 :(得分:1)
这是因为在第二种情况下,在事件调度线程(EDT)上调用jButton1ActionPerformed()
方法,并且您阻止此线程一秒钟。如果EDT被阻止,则不会更新UI。如果你希望文本在一秒钟之后改变,你不应该阻止EDT,而是使用一些背景文件,例如:
private void jButton1ActionPerformed( java.awt.event.ActionEvent evt ){
jTextField1.setText( "Hello" );
new javax.swing.SwingWorker< Void, Void >() {
@Override
protected Void doInBackground() throws Exception {
Thread.sleep( 1000 );
}
@Override
protected void done() {
jTextField1.setText( "Hello2" );
}
}.execute();
}
不要使用主动等待(while (c > a - 1000)
)。请改用Thread.sleep()
。