我使用GUI构建了以下应用程序,基于RXTX网站的示例。唯一的问题是它实际上并没有向串行设备发送任何东西。我没有包含任何与Swing GUI相关的自动生成的代码。
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Daniel
*/
public class ComForm extends javax.swing.JFrame {
/**
* Creates new form ComForm
*/
public ComForm() {
super();
initComponents();
}
void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Belea: Portu-i folosit!");
}
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 = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
open = true;
}
else
{
System.out.println("Belea: Numa porturi seriale!");
}
}
}
/**
* 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")
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
String c = this.sendField.getText();
if (open == true) {
try {
System.out.println(c);
outputStream.write(c.getBytes()); //write to serial port
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(open == false)
{
try {
connect("COM3");
}
catch ( Exception e ) {
e.printStackTrace();
}
if(open == true)
{
this.jLabel3.setText("CONECTAT!");
this.jButton1.setEnabled(false);
this.sendButton.setEnabled(true);
this.sendField.setText("");
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ComForm().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton sendButton;
private javax.swing.JTextField sendField;
// End of variables declaration
private String portName;
private CommPort commPort;
private SerialPort serialPort;
private CommPortIdentifier portIdentifier = null;
private InputStream inputStream;
private OutputStream outputStream;
private boolean open=false;
}