每次更改变量时更新JTextFields文本 [英] Update JTextFields text every change of variable

查看:63
本文介绍了每次更改变量时更新JTextFields文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,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 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(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

  1. 最重要的是,使用while(true)阻止gui使其无响应.如果您想重复,可以使用 Swing Timer .请注意,Swing计时器的任务是在事件分发线程中执行的.这意味着任务可以安全地操作组件,但是也意味着任务应该快速执行.如果任务可能需要一段时间才能执行,请考虑使用 SwingWorker 代替或除了计时器.
  2. 使用Java代码约定以提高可读性,例如,类名以大写字母开头.
  3. 您可能需要使用Observer Pattern例如使用PropertyChangeListenerPropertyChangeSupport来更新您的JTextField.
  1. The most important thing is that with while(true) blocks your gui make it irresponsive. If you want repetition you can use Swing Timer. Note that the Swing timer's task is performed in the event dispatch thread. This means that the task can safely manipulate components, but it also means that the task should execute quickly. If the task might take a while to execute, then consider using a SwingWorker instead of or in addition to the timer.
  2. Use java code conventions for readability,for example class names starts with upper case.
  3. You would need to use an Observer Pattern for example using PropertyChangeListener and PropertyChangeSupport to update your JTextField.

使用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文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆