Google Guava



  • I'm trying to figure out the EventBus from Google Guava Library. I would like to see an example of its use with regard to my task. In other words, couldn't you show an example of use?

    Let's say I have a class in which there's this inner class listening class:

        private class StopScanButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                portConnection.writeByte((byte) 0xFF);
                portConnection.writeByte((byte) 0x05);
                portConnection.writeByte((byte) 0xFF);
            } catch (SerialPortException | NullPointerException e1) {
                labelState.setText("Ошибка! Возможно вы не подключились к устройству!");
                labelState.repaint();
            }
        }
    }
    

    How can I put it on the tyre?

    P.S. It would be even better if you had shown an example of a relative application. https://github.com/Faoxis/KatinDipsach/blob/master/GUI/src/main/java/com/faoxis/gui/MainWindow.java ♪ But for the example of the class above, I would also be very grateful.



  • For starters, we need to create a class describing event:

    public class TestEvent {
    
    private final String message;
    
    public TestEvent(String message) {
        this.message = message;
    }
    
    public String getMessage() {
        return message;
    }
    

    }

    And the processor, the key here is the annotation. @Subscribewith her tire and she knows what kind of event we're gonna listen to:

    public class EventListener {
    @Subscribe
    public void listen(TestEvent event) {
    System.out.println(event.getMessage());
    }
    }

    Then we need to initial a copy of EventBus somewhere in the annex, e.g. a publicly available static field in your main class:

    public static final EventBus bus = new EventBus();

    The following shall be registered:

    bus.register(new EventListener());

    Now, wherever you are, inside ActionListener for JButton, on call:

    bus.post(new TestEvent("message"));

    All the listeners of this kind of event, get it.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2