-1

在我的代码下面,我为 gps 编写的代码是给我关于 4800 波特率的继续数据,此数据显示由“System.out.println(st)”继续显示,但相同的数据不会显示在 a.setText(st) 中,其中 a 是文本框变量。有些人知道如何像 System.out.println 行那样更新我的文本框。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.UnsupportedCommOperationException;
import javax.comm.*;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * test.java
 *
 * Created on Mar 11, 2013, 9:08:52 AM
 */
/**
 *
 * @author DJ ROCKS
 */
public class test extends javax.swing.JFrame {
    public boolean bp=true;

    /** Creates new form test */
    public test() {
        initComponents();
    }

    /** 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() {

        ok = new javax.swing.JButton();
        a = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        ok.setText("ok");
        ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okActionPerformed(evt);
            }
        });

        a.setText(" ");
        a.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(238, 238, 238)
                        .addComponent(ok)))
                .addContainerGap(124, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(a, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(67, 67, 67)
                .addComponent(ok)
                .addContainerGap(160, Short.MAX_VALUE))
        );

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

    private void okActionPerformed(java.awt.event.ActionEvent evt) {                                   
        // TODO add your handling code here:

        if(evt.getSource()==ok)
        {
            CommPortIdentifier portId = null; 
String wantedPortName="COM16";

 Enumeration portIdentifiers = CommPortIdentifier.getPortIdentifiers();


while(portIdentifiers.hasMoreElements())
{
    CommPortIdentifier pid = (CommPortIdentifier) portIdentifiers.nextElement();
    if(pid.getPortType() == CommPortIdentifier.PORT_SERIAL &&
       pid.getName().equals(wantedPortName)) 
    {
        portId = pid;
        break;
    }
}
if(portId == null)
{
    System.err.println("Could not find serial port " + wantedPortName);
    System.exit(1);
}
else
{
    System.out.println("system find gps reciever");
}
SerialPort port = null;
try {
    port = (SerialPort) portId.open(
        "RMC", 
        1);
    System.out.println("all are ok"); 
} catch(PortInUseException e) {
    System.err.println("Port already in use: " + e);
    System.exit(1);
}
            try {
                //int i=Integer.parseInt(new vps().baud_rate.getItemAt(new vps().baud_rate.getItemCount()));
               port.setSerialPortParams(
                   4800,
                   SerialPort.DATABITS_8,
                   SerialPort.STOPBITS_1,
                   SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException ex) {
                Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
            }



BufferedReader is = null;  


try {
  is = new BufferedReader(new InputStreamReader(port.getInputStream()));
  System.out.println("data is ok");
} catch (IOException e) {
  System.err.println("Can't open input stream: write-only");
  is = null;
}



 //this is variable is ouside of class and define by public it work 
    while(true)
    {

String st = null;
                try {
                    st = is.readLine();
                } catch (IOException ex) {
                    Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
                }


       System.out.println(st);
        //st = st.replace(st, "");
      a.setText(st);
      try
      {

          Thread.sleep(1000);
      }
      catch(InterruptedException ie)
      {
          System.out.printf(ie.getMessage());
      }
}
/*if (is != null) try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
            }

if (port != null) port.close();
*/
}



    }                                  

    private void aActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new test().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JTextField a;
    private javax.swing.JButton ok;
    // End of variables declaration
}
4

1 回答 1

0

似乎您可能正在尝试重写相同的字符串。我会尝试调用返回字符串而不是引用变量“st”的“get”方法。我这样做是为了避免程序尝试重写字符串的情况,因为字符串是不可变的。

我会尝试这样的事情:

private String getString()
{
try {
    String st = new String(""+is.ReadLine());
    return st;
    } catch (IOException ex) {
                Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}

使用它来引用来自 BufferedReader "is" 的新字符串:

   a.setText(getString());

此外,看起来好像您在此处的注释行中有一个代码块:

/*if (is != null) try {
            is.close();
        } catch (IOException ex) {
            Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
      if (port != null) port.close();
}*/

如果我在这里错了,请纠正我。

于 2013-03-12T18:21:32.787 回答