Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7579503
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T17:41:51+00:00 2026-05-30T17:41:51+00:00

I am trying to connect two classes together, MyJFrame and MySerialPort, using the interface

  • 0

I am trying to “connect” two classes together, MyJFrame and MySerialPort, using the interface SerialPortListener, but I am clueless as how to do it. The reason I am doing this is because yesterday I had a problem assigning data from a serial port buffer to a global String (finalString), in the MySerialPort class. This string should be returned to MyJFrame where a label displays it. The problem was that my label would display finalString before anything
was assigned to finalString, since classes were running in different threads. I posted the question on the forum and received a suggestion to use interface to connect their threads, and I modified the code according. Where do I use the keyword implements SerialPortListener and how do I get the value?

SerialPortListener Interface code

public interface SerialPortListener {

    void stringReveivedFromSerialPort(String s);

}

MyJFrame class code

public class MyJFrame extends JFrame{

    public MySerialPorts msp = new MySerialPorts();


    public MyJFrame(){

        initComponents();//draws GUI components
        initSerialPorts();//initializes serial ports

    }

    private void initSerialPorts(){

        msp.getPortName();//gets serial port's name (in this example COM1)
        msp.openPort();//opens the communication for port COM1

    }

    private String firmwareVersion(){
    //This is the method I call when I want to get the Firmware Version

        msp.getFirmwareVersion();//sends command to receive reply from serial device
        lblFirmwareVersion.setText();//label that prints the firmware version String

    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MainJFrame().setVisible(true);
            }
        });
    }

    private JLabel lblFirmwareVersion;

}

MySerialPort class code

public class MySerialPort {

//this method is using the jSSC API (java simple serial connector)
//http://code.google.com/p/java-simple-serial-connector/

    private SerialPort serialPort;
    private int iBaudRate = SerialPort.BAUDRATE_57600;
    private int iDataBits = SerialPort.DATABITS_8;
    private int iStopBits = SerialPort.STOPBITS_1;
    private int iParity = SerialPort.PARITY_NONE;
    private String portName = "";
// private String finalString = "";
//  private StringBuilder sbBuffer = new StringBuilder();

    private List<SerialPortListener> portListeners = new ArrayList<SerialPortListenerInterface>();

    public void addMyPortListener(SerialPortListener listener) {
        portListeners.add(listener);
    }

    public void removeMyPortListener(SerialPortListener listener) {
        portListeners.remove(listener);
    }

    public void getFirmwareVersion() {
        sendPortCommand("<VersFV1A2>\r\n");
    }

//    public String returnFinalString() {
//        return finalString;
//    }

    public void getPortName() {
        String[] ports = SerialPortList.getPortNames();
        portName = ports[0];
    }

    public void openPort() {

        serialPort = new SerialPort(portName);

        try {

            if (serialPort.openPort()) {

                if (serialPort.setParams(iBaudRate, iDataBits, iStopBits, iParity)) {

                    serialPort.addEventListener(new Reader(), SerialPort.MASK_RXCHAR
                            | SerialPort.MASK_RXFLAG
                            | SerialPort.MASK_CTS
                            | SerialPort.MASK_DSR
                            | SerialPort.MASK_RLSD);

                } else {
                    //Error Message - Can't set selected port parameters!
                    serialPort.closePort();
                }

            } else {
                    //Error Message - Can't open port!
            }
        } catch (SerialPortException | HeadlessException ex) {
            //Error Message - Can't open port! - Do nothing    
        }
    }

    private void sendPortCommand(String sSendPortCommand) {

        if (sSendPortCommand.length() > 0) {

            try {
                serialPort.writeBytes(sSendPortCommand.getBytes());
            } catch (Exception ex) {
                //Error Message - Error occured while sending data!
            }
        }
    }

    private class Reader implements SerialPortEventListener {

        private String sBuffer = "";

        @Override
        public void serialEvent(SerialPortEvent spe) {

            if (spe.isRXCHAR() || spe.isRXFLAG()) {

                if (spe.getEventValue() > 0) {

                    try {

                        //Read chars from buffer
                        byte[] bBuffer = serialPort.readBytes(spe.getEventValue());
                        sBuffer = new String(bBuffer);

                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                for (SerialPortListenerInterface listener : portListeners) {
                                    listener.stringReveivedFromSerialPort(sBuffer);
                                }
                            }
                        });

// The following is the code I had prior to suggestion of using invokeLater instead of invokeAndWait
//
//                        sbBuffer.setLength(0);
//
//                        SwingUtilities.invokeAndWait(
//                                new Runnable() {
//
//                                    @Override
//                                    public void run() {
//                                        sbBuffer.append(sBuffer);
//                                    }
//                                });
//
//                        finalString = new String(sbBuffer);

                    } catch (Exception ex) {
                    }

                }
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T17:41:52+00:00Added an answer on May 30, 2026 at 5:41 pm

    Here’s some code that you could add to your initSerialPorts() method, and which would open a dialog box displaying the text received from the serial port:

    msp.addMyPortListener(new SerialPortListener() {
        @Override
        public void stringReveivedFromSerialPort(String s) {
            JOptionPane.showMessageDialog(MyJFrame.this, s);
        }
    });
    

    It creates an anonymous SerialPortListener instance, which displays a dialog box containing the received text as message, and adds it to your MySerialPort msp instance.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to connect two of the same app with winsock, but the
I get this error, when trying to connect two table via manytomany: ERROR [org.hibernate.tool.hbm2ddl.SchemaUpdate]
I am trying to connect two widgets through the signals/slots option but I keep
I have two local databases I'm trying to connect to using Java's Connection class.
i'm trying to make a program that will connect two points that i click
I would like to connect two draggable divs using jsPlumb. However when I use
I'm trying to connect a C# application (using Visual C# 2008 Express Edition) to
We are trying to connect two Hyper-V VMs through a serial port. Hyper-V exposes
I'm trying to follow this tutorial in order to connect to an external database
I've been trying to add Facebook Connect to a website, but it didn't seem

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.