开发者

"Nested" ActionListeners in Java?

开发者 https://www.devze.com 2023-01-31 16:41 出处:网络
I am develop[ing an application where entry of a ticker symbol in a textfield invokes the plot of a stock price chart.I also want to modify this chart in certain ways by selecting menu items.

I am develop[ing an application where entry of a ticker symbol in a textfield invokes the plot of a stock price chart. I also want to modify this chart in certain ways by selecting menu items.

In software terms, it would be easiest if I could have the menu item ActionListeners change the value of a status parameter, then simply call the TextField ActionListener to replot the chart.

There are of course other ways to achieve this, but is there any way to call an action listener from within another actionlistener. The compiler doesn't like the开发者_如何学运维 idea.

Thanks in advance for any insights.

John Doner


One way to do this would be to make your ActionListeners "thin" and have them delegate to a private method somewhere, for example:

class Controller {
    ... // variable declarations etc

    public Controller() {
        textField.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
            setStockSymbol(...);
            replot();
        }});
        menuItem.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {
            setStatusParameter(...);
            replot();
        }});
    }

    private void replot() {
        // Do whatever
    }
}

This factors out the replotting part from both ActionListeners. If you need other code paths to trigger a replot then it is now simple to implement those, and your plotting code is now nicely separated from the parameter update code.


You are trying to create a class that acts as both a subscriber and a publisher. Simply have your class implement the ActionListener interface, but also provide a way to subscribe to ActionListeners in your class.

public class MyActionSubPub
{
    private List<ActionListener> downstreams = new ArrayList<ActionListener>();
    public MyActionSubPub( AbstractButton(or whatever) button )
    {
        button.addActionListener( this );
    }
    public addActionListener( ActionListener listener )
    {
        downstreams.add( listener );
    }
    public void actionPerformed( ActionEvent event )
    {
        ... do your stuff ...
        ... loop through all downstreams, call actionPerformed on each...
    }
}

Alternatively, you could create an adapter that sends the event to one class, waits for it to return, then sends the action to the next class.

0

精彩评论

暂无评论...
验证码 换一张
取 消