java - 向 COM 端口发送字符串

标签 java serial-port jbutton

第一个项目,只是出于兴趣,以便我可以学习。

我正在尝试制作一个应用程序,它将通过通信端口发送字符串。下面是我的 GUI(第一次尝试!)

我已经创建了按钮,它们可以执行一些操作,但现在我需要添加 com 端口功能。

请有人给我指点一下吗?请用最简单的语言。我是自学成才的。

import java.awt.GridLayout;
import java.io.*;
import javax.swing.*;

import java.util.*;



public class AlarmGenerator extends javax.swing.JFrame {

public AlarmGenerator() {
    initComponents();
}


private void initComponents() {

    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton4 = new javax.swing.JButton();


    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextField1.setText("Enter Custom String Here");
    jTextField2.setText("Result");
    jButton1.setText("Alarm1");
    jButton2.setText("Alarm2");
    jButton3.setText("Alarm3");
    jButton4.setText("Custom Alarm");

    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)    
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jTextField1)
                    .addComponent(jTextField2)

    )));
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()

            .addComponent(jButton1)
            .addComponent(jButton2)
            .addComponent(jButton3)
            .addComponent(jButton4)
            .addComponent(jTextField1)
            .addComponent(jTextField2)

            .addContainerGap(0, Short.MAX_VALUE))
    );

    pack();

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

        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Alarm 1 Activated, String: "+alarm1);
        }
    });

    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }

        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Alarm 2 Activated, String: "+alarm2);
        }
    });

    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }

        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Alarm 3 Activated, String: "+alarm3);
        }
    });

    jButton4.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton4ActionPerformed(evt);
        }

        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
            jTextField2.setText("Custom alarm, string sent: "+jTextField1.getText ());
        }
    });
}                       

public static void main(String args[]) {        

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new AlarmGenerator().setVisible(true);


        }
    });


}

// Variables declaration                    
private static javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
String alarm1 = "Hello";
String alarm2 = "Bye";
String alarm3 = "Custom";
// End of variables declaration                   
}

2 级

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TwoWaySerialComm {
public TwoWaySerialComm() {
    super();
}

void connect(String portName) throws Exception {
    CommPortIdentifier portIdentifier = CommPortIdentifier
            .getPortIdentifier(portName);
    if (portIdentifier.isCurrentlyOwned()) {
        System.out.println("Error: Port is currently in use");
    } else {
        CommPort commPort = portIdentifier.open(this.getClass().getName(),
                2000);

        if (commPort instanceof SerialPort) {
            SerialPort serialPort = (SerialPort) commPort;
            serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

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

            (new Thread(new SerialReader(in))).start();
            (new Thread(new SerialWriter(out))).start();

        } else {
            System.out
                    .println("Error: Only serial ports are handled by this example.");
        }
    }
}

/** */
public static class SerialReader implements Runnable {
    InputStream in;

    public SerialReader(InputStream in) {
        this.in = in;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            while ((len = this.in.read(buffer)) > -1) {
                System.out.print(new String(buffer, 0, len));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

/** */
public static class SerialWriter implements Runnable {
    OutputStream out;

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

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

public static void main(String[] args) {
    try {
        (new TwoWaySerialComm()).connect("COM3");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

最佳答案

看看这个链接。

它将更深入地了解如何通过 COM 端口发送数据

How to send data to COM PORT using JAVA?

此页面链接到一些可能的答案

Java Serial Communication on Windows

Is there Java library or framework for accessing Serial ports?

Reading serial port in Java

另外两个答案基本上与读取串行端口的答案相同。

private TwoWaySerialComm twoWaySerCom;

public AlarmGenerator() {

    initComponents();   

    twoWaySerCom = new TwoWaySerialComm();

    try {

        twoWaySerCom.connect("COM1");
    } 
    catch (Exception e) {

        e.printStackTrace();
    }
}

我注意到你有多个

 public static void Main(string[] args)

在您的项目中,这些是项目条目,一个就足够了。

关于java - 向 COM 端口发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27959711/

相关文章:

Java Hangman - 单击时如何为 JButton 分配字母?

java - ActionListener 中预期的标识符

java - JButton setBackground 不起作用

java - List<String> 的列表到字符串有序的字符串数组

java - Swing App 与 Spring DM 启动问题

java - 集会中特定用户故事的缺陷

c++ - 根据多个终止字符从 UART 收集数据

java - 使用 JPQL 通过 UCanAccess 驱动程序查询 MS-Access 数据库

delphi - 如何判断一台机器物理上是否有串口?

c# - 如何使用 asp.net 4 在 C# 中获取所有可用 Com 端口的列表