简体   繁体   中英

Java: How to generate an event from a socket readline()?

I have messages (lines) coming in from a tcp socket, (the messages originating from a CAN gateway). On selected messages, after selection and parsing, I want to update a swing GUI form (eg generated in Netbeans).

I read that the swing update must be driven from the event handler, and there are many examples, but they are based on button pushes, slider changes, etc., and not incoming socket data, (or serial ports). It appears that I need to make the handling of a 'readline' of a socket generate an event, however I don't find examples and given that it has to be a common problem and maybe I'm on the wrong track and there might be simpler alternatives.

Use SwingUtilities.invokeLater() to run arbitrary code on the swing event thread. for example:

    String stuff = socket.readLine();
    if (myStuff(stuff)) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // do any updates to swing ui here
            }
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM