好吧所以我在这里遇到了一些问题首先我在尝试连接到com端口3时不断收到nullPointerException,我尝试了几种不同的方法,首先选择端口然后通过搜索端口并尝试它。第二次我不断为我的RXTX lib得到这个32位64位不匹配的异常,所以我修复了它然后想出了这个错误
WARNING: RXTX Version mismatch
Jar version = RXTX-2.2pre1
native lib Version = RXTX-2.2pre2
Failed to open COM3(java.lang.NullPointerException)
Failed to open COM3(java.lang.NullPointerException)
我似乎无法弄明白,因为我从同一个地方得到了它们。但是我的问题仍然是Null指针异常,所以这里是我的代码视图
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.border.*;
public class SPMRV2 extends MyFrame{
UserSerialV2 communicator = null;
//combo Box for Com port selection
public JComboBox comBox = new JComboBox(new String[] {"COM1", "COM2", "COM3", "COM4", "COM5"});
private JButton selectBtn = new JButton("Select");
//Buttons or the starting and stopping of the program Start will initialize the program stop will close the port for communication
private JButton startBtn = new JButton("Connect");
private JButton stopBtn = new JButton("Disconnect");
//message Area for log
private JTextArea logDisplay = new JTextArea(" ", 200, 45);
private JTextField newTextFile = new JTextField();
private JLabel fileLabel = new JLabel("Please Enter The File You Wish To Log To: \n");
public SPMRV2(){
initComponents();
createObjects();
}
public void createObjects(){
communicator = new UserSerialV2();
}
public void initComponents(){
//set Button Listeners
ButtonListener selected = new ButtonListener();
startBtn.addActionListener(selected);
stopBtn.addActionListener(selected);
selectBtn.addActionListener(selected);
JPanel comSelect = new JPanel();
comSelect.setLayout(new GridLayout(4,1));
comSelect.setBorder(new TitledBorder("Select Your Com Port"));
comSelect.add(comBox);
comSelect.add(fileLabel);
comSelect.add(newTextFile);
comSelect.add(selectBtn);
JPanel action = new JPanel();
action.setLayout(new FlowLayout());
action.setBorder(new TitledBorder("Start/Stop console"));
action.add(startBtn);
action.add(stopBtn);
JPanel leftContainer = new JPanel();
leftContainer.setLayout(new BorderLayout());
leftContainer.add(comSelect, BorderLayout.NORTH);
leftContainer.add(action, BorderLayout.SOUTH);
JPanel rightContainer = new JPanel();
rightContainer.setLayout(new FlowLayout());
rightContainer.setBorder(new TitledBorder("Members Logged"));
rightContainer.add(logDisplay);
JPanel wrapper = new JPanel();
wrapper.setLayout(new BorderLayout());
wrapper.add(leftContainer, BorderLayout.WEST);
wrapper.add(rightContainer, BorderLayout.EAST);
add(wrapper);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SPMRV2().setVisible(true);
}
});
}
//Start/Stop/Select/Quit Button Listener Class
class ButtonListener implements ActionListener{
String userFile = "";
String newComPort = "";
public void actionPerformed(ActionEvent e){
if(e.getSource() == selectBtn){
comBox.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
}
});
newComPort = (String)comBox.getSelectedItem();
userFile = newTextFile.getText();
communicator.searchForPorts(newComPort);
logDisplay.append(communicator.searchForPorts(newComPort));
logDisplay.append("You are going to be communicating through Comm Port: " + newComPort + "\n");
logDisplay.append("And you will be Logging info to text File: " + userFile + "\n");
}
if(e.getSource() == startBtn){
communicator.initiate(newComPort);
if (communicator.getConnected() == true){
if (communicator.readerStream() == true){
communicator.startListener();
communicator.logging(userFile);
}
}
}else if(e.getSource() == stopBtn){
communicator.disconnect();
}
}
}
}
这是我正在使用的gui设置,以下是我的串行程序
import gnu.io.*;
import java.awt.Color;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.TooManyListenersException;
public class UserSerialV2 extends SPMR implements SerialPortEventListener{
//create string to store exception readout in
String excepText = "";
public boolean bConnected = false;
/*
Creates a file and additional info for serial logging storage
*/
public static String file = "";
public static String data = "";
public static final java.util.Date LOG_DATE = new java.util.Date();
//for containing the ports that will be found
private Enumeration serialPorts = null;
//map the port names to CommPortIdentifiers
private HashMap portMap = new HashMap();
//this is the object that contains the opened port
private CommPortIdentifier selectedPortIdentifier = null;
private SerialPort serialPort = null;
//input and output streams for sending and receiving data
public InputStream input = null;
private OutputStream output = null;
//the timeout value for connecting with the port
final static int TIMEOUT = 5000;
//some ascii values for for certain things
final static int SPACE_ASCII = 32;
final static int DASH_ASCII = 45;
final static int NEW_LINE_ASCII = 10;
public UserSerialV2(){
}
public String searchForPorts(String userComm){
serialPorts = CommPortIdentifier.getPortIdentifiers();
while (serialPorts.hasMoreElements()){
CommPortIdentifier currentPort = (CommPortIdentifier)serialPorts.nextElement();
//get only serial ports
if (currentPort.getName() == userComm){
portMap.put(currentPort.getName(), currentPort);
data = "Found Com Port 3";
}
}
return data;
}
public void initiate(String comPort){
String selectedPort = comPort;
selectedPortIdentifier = (CommPortIdentifier)portMap.get(selectedPort);
CommPort commPort = null;
try{
//the method below returns an object of type CommPort
commPort = selectedPortIdentifier.open("User Serial APP", TIMEOUT);
//the CommPort object can be casted to a SerialPort object
serialPort = (SerialPort)commPort;
serialPort.setSerialPortParams(9600, 8, 1, 0);
setConnected(true);
//logging
data = selectedPort + " opened successfully.";
// //CODE ON SETTING BAUD RATE ETC OMITTED
// try {
// serialPort.setSerialPortParams(9600,
// SerialPort.DATABITS_8,
// SerialPort.STOPBITS_1,
// SerialPort.PARITY_NONE);
// } catch (UnsupportedCommOperationException e){
// System.out.println(e);
// }//end try catch block
}
catch (PortInUseException e){
excepText = selectedPort + " is in use. (" + e.toString() + ")";
System.out.println(excepText);
}
catch (Exception e){
excepText = "Failed to open " + selectedPort + "(" + e.toString() + ")";
System.out.println(excepText);
}
}
//method to collect input from the port
public boolean readerStream() {
//boolean value variable for input stream
boolean success = false;
try{
input = serialPort.getInputStream();
success = true;
return success;
}catch(IOException e){
excepText = "I/O Streams Failed To Open" + "(" + e.toString() + ")";
System.out.println(excepText);
return success;
}
}//end readerStream
//method to start listener when user connects to port
public void startListener(){
try{
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
}catch(TooManyListenersException e){
excepText = "Too many listeners" + "(" + e.toString() + ")";
System.out.println(excepText);
}
}
//Method to disconnect from the serial port when the user is finished with logging
public void disconnect(){
try{
serialPort.removeEventListener();
serialPort.close();
input.close();
data = "Disconnected";
setConnected(false);
}catch(Exception e){
excepText = "(" + e.toString() + ")";
System.out.println("Disconnect Problem " + excepText);
}
}
public void serialEvent(SerialPortEvent event){
if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE){
try{
byte singleData = (byte)input.read();
if (singleData != NEW_LINE_ASCII){
this.data = new String(new byte[] {singleData});
}
else
{
this.data = "\n";
}
}catch(Exception e){
excepText = "(" + e.toString() + ")";
System.out.println("Serial Event Problem " + excepText);
}
}
}
final public boolean getConnected()
{
return bConnected;
}
public void setConnected(boolean bConnected)
{
this.bConnected = bConnected;
}
public String logging(String file){
UserLogFile log = new UserLogFile();
log.openFile(file);
log.addLog(data + LOG_DATE);
log.closeFile();
return data;
}
}
我之前已经问过这个问题,但似乎无法得到任何答复,任何机构都对可能导致问题的原因有任何想法?
谢谢,
哦,在代码中提到了userlogFile,它只是一个简单的写作类,我用来将信息传递给登录用户的文本文件。