【问题标题】:Display data in jtextfield one by one not all at a time不是一次全部显示 jtextfield 中的数据
【发布时间】:2014-12-10 08:22:03
【问题描述】:

下面是代码。它从 com 端口读取并在 netbeans gui 创建的文本字段中显示数据。此代码运行。它实际上合并了5个com数据并在最后一次显示。

我想在 gui 中一一显示单个数据。程序结束时并非所有 5 个数据都在一起。其实我想让 gui 运行,然后文本字段填充 5 从 com 端口读取的数据。

package learn;

import jssc.SerialPort;
import jssc.SerialPortException;

public class gui extends javax.swing.JFrame {

/**
 * Creates new form gui
 */
public gui() {
    initComponents();
    for (int i=0;i<5;i++)
        comport();
}

private void comport() {
    SerialPort serialPort = new SerialPort("COM3");
    int count = 1;
    try {
        serialPort.openPort(); //Open serial port
        serialPort.setParams(9600, 8, 1, 0);//Set params.
        byte[] buffer = serialPort.readBytes(32);//Read 10 bytes from serial port
        final String readed = new String(buffer);
        //  System.out.println("««Readed from COM"  + ": " + readed);

        jTextArea1.append(readed+ "\n" );
        serialPort.closePort();//Close serial port   
    } catch (SerialPortException ex) {
       System.out.println(ex);
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    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(27, 27, 27)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(132, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(152, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

/**
 * @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(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(gui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(gui.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 gui().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
// End of variables declaration                   

}

【问题讨论】:

  • 在单独的线程中阅读和附加内容
  • 你认为它会起作用吗?我需要先显示 GUI。然后在文本字段上附加 com 数据。使用此当前代码 comport() 方法先执行,然后将数据一起显示。
  • 可能您必须使用字符串缓冲区将每个读取的字符串与换行符连接起来,并将其附加到 jTextArea1?我的印象是读取的字符串是作为长字符串生成的,所有值都在一起,或者您可以根据某些特定字符拆分此字符串。

标签: java swing textfield


【解决方案1】:
package learn;

import jssc.SerialPort;
import jssc.SerialPortException;

public class GUI extends javax.swing.JFrame implements Runnable{

    /**
     * Creates new form GUI
     */

    Thread thread;
    public GUI() {
        initComponents();
        thread = new Thread(this);
        thread.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @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(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GUI.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 GUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   

    @Override
    public void run() {
      for (int i=0;i<5;i++)
    comport();
    }
    private void comport(){

      SerialPort serialPort = new SerialPort("COM3");

      int count = 1;


  //  while (count < 11) {
     try {

        serialPort.openPort();//Open serial port
        serialPort.setParams(9600, 8, 1, 0);//Set params.
        byte[] buffer = serialPort.readBytes(32);//Read 10 bytes from serial port
        final String readed = new String(buffer);
      //  System.out.println("≪≪Readed from COM"  + ": " + readed);

        jTextArea1.append(readed+ "\n" );
        serialPort.closePort();//Close serial port

    }
    catch (SerialPortException ex) {
       System.out.println(ex);
    }
   //count++;
   // }

}
}

试试这样吧,我没做太多改动,只是创建了一个线程。

【讨论】:

  • 给出错误没有为 Thread 找到合适的构造函数。对此有任何解决方案。
  • 我创建了线程。现在问题是gui正在运行。但 GUI 中没有数据。覆盖运行功能不运行。
  • 您启动了线程并运行不工作?尝试在运行方法中打印一些东西!
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2018-12-25
  • 2021-04-01
  • 2017-01-21
  • 2013-02-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多