Search code examples
javanetbeanstooltip

Run method from another method - Java


I want a message to display in the toolbar when the timer runs out. Here is my code:

private void startJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                     

        Timer oneHour = new Timer(3600000, //RunTheActionPerformedShownBelow);

} 

public void ReminderTrayIco() {

item3.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            trayIcon.displayMessage("Title", "Message", TrayIcon.MessageType.ERROR);
        }
    });
}

What I'm trying to accomplish is to run the code that is under 'item2.addActionListener' when the timer reaches 0. I feel as if there is a very simple solution right under my nose, but I just can't figure it out. Any help is appreciated!


Solution

  • Start by writing a custom ActionListener class which performs the required operation...

    public class TrayMessageActionListener implements ActionListener {
        private TrayIcon trayIcon;
    
        public TrayMessageActionListener(TrayIcon trayIcon) {
            this.trayIcon = trayIcon;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            trayIcon.displayMessage("Title", "Message", TrayIcon.MessageType.ERROR);
        }
    
    }
    

    Now you can use it with item3...

    item3.addActionListener(new TrayMessageActionListener(trayIcon));
    

    and the timer...

    Timer oneHour = new Timer(3600000, new TrayMessageActionListener(trayIcon));
    oneHour.setRepeats(false);
    

    This, obviously means that both item3 and the Timer code will need to have access to the same instance of TrayIcon when they are created