簡體   English   中英

使用Swing和RXTX的Java RS232通信

[英]Java RS232 communication using Swing and RXTX

我正在嘗試使用串行端口在PC(使用Netbeans的Windows 7和RXTX)之間進行通信。 我對串行事件有一個問題(公共無效serialEvent(SerialPortEvent arg0))。 此事件應獲取數據並將其寫入標簽(jLabel1.setText(“ sfazds”))中。 不幸的是,此事件不會更改標簽文本,我現在也不為什么。 下面是我的代碼:

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class RS extends javax.swing.JFrame implements SerialPortEventListener{

    static OutputStream out;
    static InputStream in;

    public RS() {
        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() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

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

        jLabel1.setText("jLabel1");

        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(54, 54, 54)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(203, 203, 203)
                        .addComponent(jLabel1)))
                .addContainerGap(217, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jButton1)
                .addGap(34, 34, 34)
                .addComponent(jLabel1)
                .addContainerGap(222, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        byte[] b = new byte[2];
        b[0] = 'a';
        b[1] = 'b';
        try{
            out.write(b);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }                                        

    private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
        try{
            (new RS()).connect("COM3");
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }                                 

    void connect(String portName) throws Exception{
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()){
            JOptionPane.showMessageDialog(null, "Błąd: Port jest obecnie w użyciu");
        }
        else{
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
            if (commPort instanceof SerialPort){
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                (new Thread(new SerialWriter(out))).start();
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            }     
            else{
                JOptionPane.showMessageDialog(null, "Tylko port szeregowy może być podłączony!");
            }
        }
    }
    @Override
    public void serialEvent(SerialPortEvent arg0) {
            int data;
            byte[] buffer = new byte[1024];
            try{
                int len = 0;
                while ( ( data = in.read()) > -1 ){
                    if ( data == '\n' ) {
                        break;
                    }
                    buffer[len++] = (byte) data;
                }
                System.out.print(new String(buffer,0,len));
                jLabel1.setText("sfazds");
                JOptionPane.showMessageDialog(null, new String(buffer,0,len));
            }
            catch ( IOException e ){
                System.exit(-1);
            }             
        }

    public static class SerialWriter implements Runnable{
        OutputStream out;

        public SerialWriter(OutputStream out){
            this.out = out;
        }

        @Override
        public void run(){
            try{
                int c = 0;
                while ((c = System.in.read()) > -1){
                    this.out.write(c);
                }
            }
            catch(IOException e){
                System.exit(-1);
            }
        }
    }

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

您的輸出可能未與EventDispatcherTread同步。 請嘗試以下操作:

    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            jLabel1.setText("sfazds");
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM