我找到了有關該問題的許多答案,但我仍然不明白為什麼我的應用程式不會引發任何異常.
我在NetBeans 8中建立了一個新的Java表單應用程式.
我的表單是通過以下主要方法建立和顯示的:
public static void main(String args[])
{
//
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(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(MainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new MainForm().setVisible(true);
}
});
}
是以,此新的Runnable将建立新的MainForm并将其設定為可見.
然後,在我的代碼中,我啟動了新線程,這些線程更新了一些jButton和jTextField.代碼如下:
private void updateUI() {
updateUIThread = new Thread(() ->
{
while (true) {
try {
jtfIP.setEnabled(!Start && !autoRec);
jtfPort.setEnabled(!Start && !autoRec);
jtfSlaveID.setEnabled(!Start && !autoRec);
jtfTimeout.setEnabled(!Start && !autoRec);
jtfReqInterval.setEnabled(!Start && !autoRec);
jCheckBox1.setEnabled(!Start && !autoRec);
jCBReconnect.setEnabled(!Start && !autoRec);
if (db != null) {
if (!db.getIsOpen()) {
jPBD.setBackground(Color.RED);
jPBD.setForeground(Color.WHITE);
jPBD.setText("ER");
} else {
jPBD.setBackground(Color.GREEN);
jPBD.setForeground(Color.BLACK);
jPBD.setText("OK ");
}
} else {
jPBD.setBackground(Color.RED);
jPBD.setForeground(Color.WHITE);
jPBD.setText(" ER ");
}
if (autoRec){
jbtnConnect.setText("Auto");
if (Start && Connected) {
jbtnConnect.setForeground(Color.BLACK);
jbtnConnect.setBackground(Color.GREEN);
} else {
jbtnConnect.setForeground(Color.WHITE);
jbtnConnect.setBackground(Color.RED);
}
} else {
if (Start) {
jbtnConnect.setText("Disconnect");
jbtnConnect.setForeground(Color.BLACK);
jbtnConnect.setBackground(Color.GREEN);
} else {
jbtnConnect.setText("Connect");
jbtnConnect.setForeground(Color.WHITE);
jbtnConnect.setBackground(Color.RED);
}
}
jtfErroriCitire.setText(String.valueOf(totalErrors));
try
{
Thread.sleep(300);
jPanel4.repaint(1);
}
catch (InterruptedException ex)
{
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
catch (Exception ex) {
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
updateUIThread.start();
}
并且還有其他像以上這樣啟動的線程,在這裡我得到了不同的值,這些值在上述線程中進行了更新.
我的問題是為什麼我的代碼不會對從另一個線程更新的UI元素引發任何異常?我沒有使用SwingUtilities.invokeLater(new Runnable(){//代碼在這裡});
而且我的代碼執行得很好…
謝謝!