您好,Hello II是Java的新手,我试图编写一个非常简单的练习来练习,我创建了一个Jclass来从数据库中读取参数,并将其保存在名为"estado"的变量中,并将JFrame保存到显示该变量的值,该变量在数据库中随机变化.
Hello I I´m a very newbie in Java and I´m trying to write a very simple excercise to practice, I created a Jclass to read the parameter from a DB and save it in a variable called "estado" and a JFrame to show the value of this variable who is changing randomly in DB.
程序读取MySql DB并将所需的数据存储在Java变量中,例如这些类:
The program read a MySql DB and store the data needed in a Java variable like these class:
package Paquete_domotica; import java.io.*; import java.sql.*; public class domotica { public static int estado; boolean loop = true; public domotica() throws IOException { while(loop) { try { DriverManager.registerDriver(new org.gjt.mm.mysql.Driver()); Connection conexion = DriverManager.getConnection ( "jdbc:mysql://localhost/XXX","XXXX", "XXXX"); Statement s = conexion.createStatement(); ResultSet rs = s.executeQuery ("select id, nombre, valor from data"); while (rs.next()) { if (rs.getInt ("id") == 20) { estado = rs.getInt ("valor"); } } rs.close(); conexion.close(); } catch (SQLException e) { e.printStackTrace(); } } } }存储的变量称为"estado",这些变量为1或0,我试图在以下Jframe中对这些变量的每次更改都更改jTextField1的值:
The variable stored is called "estado", these variable is 1 or 0 and I´m trying that every change of these variable make a change of the value of jTextField1 in the following Jframe:
package Paquete_domotica; import java.awt.event.ActionListener; import java.io.IOException; public class JFramedomotica extends javax.swing.JFrame { int numeroRecibido; public JFramedomotica() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jTextField1 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField1.setText("SIN DATOS"); jTextField1.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); jTextField1.setEnabled(false); jTextField1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTextField1MouseClicked(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(110, 110, 110) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(154, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(138, 138, 138) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(142, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) { jTextField1.setText(String.valueOf(domotica.estado)); } public static void main(String args[]) throws IOException { /* 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 download.oracle/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(JFramedomotica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(JFramedomotica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(JFramedomotica.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(JFramedomotica.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 JFramedomotica().setVisible(true); } }); new domotica(); } // Variables declaration - do not modify private javax.swing.JTextField jTextField1; // End of variables declaration }如您所见,我可以使用
private void jTextField1MouseClicked(java.awt.event.MouseEvent evt) { jTextField1.setText(String.valueOf(domotica.estado)); }但是使用此代码,我必须单击鼠标以刷新jTextField1,我不知道如何在每次更改"estado"时更新jTextField1.
But with this code I have to click mouse to refresh the jTextField1, I don´t know how to update jTextField1 at every change of "estado".
推荐答案您有很多痛苦的代码,很难在哪里开始,使用的是public static estado变量,这在OOP中是非常糟糕的设计. Swing是基于事件的系统.因此,让我们看看一些技巧
You have a lot painful code that is hard where to begin, you are using a public static estado variable, that is a very bad design in OOP. Swing is an event based system. So let's see some tips
使用SwingWorker的示例.
public class Domotica extends SwingWorker<Void, Void> { private Integer estado; private boolean loop = true; @Override protected Void doInBackground() throws Exception { while (loop) { try { DriverManager.registerDriver(new org.gjt.mm.mysql.Driver()); Connection conexion = DriverManager.getConnection( "jdbc:mysql://localhost/XXX", "XXXX", "XXXX"); java.sql.Statement s = conexion.createStatement(); ResultSet rs = s.executeQuery("select id, nombre, valor from data"); while (rs.next()) { if (rs.getInt("id") == 20) { setEstado(rs.getInt("valor")); } } //think in some connection pool to not open and close everytime rs.close(); conexion.close(); } catch (SQLException ex) { ex.printStackTrace(); } Thread.sleep(100); } return null; } public void setEstado(Integer estado) { int oldEstado = this.estado; this.estado = estado; firePropertyChange("estado", oldEstado, this.estado); } }然后在您的JFrame中可以执行此操作.
Then in your JFrame you can do this.
public JFramedomotica() { initComponents(); SwingWorker<Void,Void> worker = new Domotica(); worker.addPropertyChangeListener(new PropertyChangeListener(){ @Override public void propertyChange(PropertyChangeEvent evt){ if(evt.getPropertyName().equals("estado")){ jTextfield1.setText(evt.getNewValue().toString()); } } }); worker.execute(); }更多推荐
每次更改变量时更新JTextFields文本
发布评论