-1

所以,我正在制作一个通过发送命令与传感器通信的程序。但是,当我尝试单击 GUI 中的按钮时,会出现两个错误:空指针异常和 portinuse 异常,这会阻止按钮工作。我该如何解决?

简单阅读类:

import java.awt.event.ActionListener;
import java.io.*;
import java.util.*; 
import javax.comm.*;
import javax.swing.*;



public class SimpleRead  {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static  PrintStream os;
    static BufferedReader is;
    static java.util.Timer t = new java.util.Timer();
    static TimersTask tt = new TimersTask();

    public static void main(String[] args) {

        GUI GUI = new GUI();
        JFrame window = new JFrame("DI-100"); 
        window.setSize(700, 300); 
        window.setVisible(true); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(GUI);

        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        String wantedPortName;
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            ArrayList<String> serialports = new ArrayList<String>();
            serialports.add(portId.getName());
            String[] ports = new String[serialports.size()];
            ports = serialports.toArray(ports); 
            GUI.jComboBox2 = new JComboBox(ports);
            GUI.jComboBox2.addActionListener(GUI.jComboBox2);
            wantedPortName = (String) GUI.jComboBox2.getSelectedItem();


            while (portList.hasMoreElements()) { 
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                  portId.getName().equals(wantedPortName)) {
                    CommPortIdentifier pid = portId;
                    SerialPort port = null;


                    try {
                        port = (SerialPort) portId.open("OpenPort", 1000);

                    } catch(PortInUseException e) {
                        System.err.println("Port already in use: " + e);
                    }   



                    try {
                        port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                    }
                    catch (UnsupportedCommOperationException e) {
                        System.out.println("you suck");
                    }



                    try {
                        os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
                    }
                    catch (IOException e) {
                        System.err.println("Can't open input stream: write-only");
                    }



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



                    try{
                        os = new PrintStream(port.getOutputStream(), true);
                    } catch (IOException e){   
                    }
                }
                else {
                }
            }
        }
    }
}

TimersTask 类:

import java.io.IOException;
import java.util.*;

public class TimersTask extends TimerTask{
    @Override
    public void run() {
        SimpleRead.os.print("W");
        try {           
            String returnvalue = SimpleRead.is.readLine(); 
            System.out.println(returnvalue);
            GUI.jTextField1.setText(returnvalue); 
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {    
            }
            //is.readLine(); // Second read will remove the extra line feed that AT generates as 
        } catch (IOException e){    
        }
    }
}
4

1 回答 1

0

OK so here's what I think is happening. You're trying to open the port: port = (SerialPort) portId.open("OpenPort", 1000);, and that fails for whatever reason. You then go on to use it again: port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);, except that it's NULL at this point, so your program explodes.

SimpleRead class:

import java.awt.event.ActionListener;
import java.io.*;
import java.util.*; 
import javax.comm.*;
import javax.swing.*;

public class SimpleRead  {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static PrintStream os;
    static BufferedReader is;
    static java.util.Timer t = new java.util.Timer();
    static TimersTask tt = new TimersTask();

    public static void main(String[] args) {

        GUI GUI = new GUI();
        JFrame window = new JFrame("DI-100"); 
        window.setSize(700, 300); 
        window.setVisible(true); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(GUI);

        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        String wantedPortName;
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            ArrayList<String> serialports = new ArrayList<String>();
            serialports.add(portId.getName());
            String[] ports = new String[serialports.size()];
            ports = serialports.toArray(ports); 
            GUI.jComboBox2 = new JComboBox(ports);
            GUI.jComboBox2.addActionListener(GUI.jComboBox2);
            wantedPortName = (String) GUI.jComboBox2.getSelectedItem();


            while (portList.hasMoreElements()) { 
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                  portId.getName().equals(wantedPortName)) {
                    CommPortIdentifier pid = portId;
                    SerialPort port = null;


                    try {
                        port = (SerialPort) portId.open("OpenPort", 1000);
                        port.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                        os = new PrintStream(port.getOutputStream(), true, "ISO-8859-1");
                        is = new BufferedReader(new InputStreamReader(port.getInputStream()));
                        os = new PrintStream(port.getOutputStream(), true); // you had this line in your original code.  Is this really necessary, since you have a similar line 2 lines before it?
                    } catch(PortInUseException e) {
                        System.err.println("Port already in use: " + e);
                    } catch (UnsupportedCommOperationException e) {
                        System.out.println("you suck");
                    } catch (IOException e) {
                        System.err.println("Can't open input or output stream");
                    }
                }
                else {
                }
            }
        }
        try {
            os.close();
        } catch (Exception ex) {
            //already closed
        }
        try {
            is.close();
        } catch (Exception ex) {
            //already closed
        }
        // close the port here
    }
}

TimersTask class:

import java.io.IOException;
import java.util.*;

public class TimersTask extends TimerTask{
    @Override
    public void run() {
        SimpleRead.os.print("W");
        try {           
            String returnvalue = SimpleRead.is.readLine(); 
            System.out.println(returnvalue);
            GUI.jTextField1.setText(returnvalue); 
            Thread.sleep(1000);
            //is.readLine(); // Second read will remove the extra line feed that AT generates as 
        } catch (IOException e){    
        } catch (InterruptedException e) {    
        }
    }
}

This fixes one of your problems, and a whole lot of issues you didn't know you had. the way a try/catch is designed to work is so when something fails, the rest of the code inside the block does not run, because it is dependent on what failed. Your code, instead, would simply run through all that throwing exception after exception as it failed.

The underlying problem is the PortInUseException, which is self-explanatory. Something else is already using the port. Check your code (here and elsewhere) to make sure you aren't trying to open the port twice (like, if you click the button more than once perhaps?), and if that doesn't solve the issue, there may be another program on your computer grabbing the port.

"Remember kids, always close your ports when you're done with them!"

于 2013-06-19T18:02:42.320 回答