Question

The only thing that needs to change on the serial port for this application is the port name/number. JSSC is able to update a combobox like this

private void jComboBoxCommPortFocusGained(java.awt.event.FocusEvent evt) {                                              
    SetPortNames();
}                                             
private void SetPortNames() {
    jComboBoxCommPort.removeAllItems();
    String[] portNames = SerialPortList.getPortNames();
    for (String portName : portNames) {
        jComboBoxCommPort.addItem(portName);
        System.out.println(portName);
    }
}                                            

But the ActionEvent

private void jComboBoxCommPortActionPerformed(java.awt.event.ActionEvent evt) {                                                  
    InitializeSerialPort(jComboBoxCommPort.getSelectedItem().toString());
}                                                 
private void InitializeSerialPort(String port) {
    try {
        if (serialPort.getPortName().contentEquals(port)) return;
        if (serialPort.isOpened()) serialPort.closePort();
        serialPort = new SerialPort(port);
        serialPort.openPort();
        serialPort.setParams(115200, 8, 1, 0);
        serialPort.setEventsMask(SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS);
        serialPort.addEventListener(new SerialPortReader());
    }
    catch (SerialPortException ex) {
        System.out.println(ex);
    }
}

breaks the combobox and causes this

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at stb.serialization.JFrameSerialization.jComboBoxCommPortActionPerformed(JFrameSerialization.java:157)
    at stb.serialization.JFrameSerialization.access$300(JFrameSerialization.java:19)
    ...

What is the correct way to change a JSSC serial port?

Was it helpful?

Solution

NullPointerException was caused by null jssc.SerialPort. Fixed by replacing

static SerialPort serialPort;

with

static SerialPort serialPort = new SerialPort("");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top