Listening to an ActionListener from another class?

I have a JPanel with a JButton.

publicclass OkButtonPanelextends javax.swing.JPanel{

public OKButtonPanel(){

JButton okButton =new JButton("OK");

okButton.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent ae){

System.out.println("You pressed the ok button!");

}

});

......

I add this JPanel to a JDialog. I want this dialog to close whenever the ok button is pressed.

I know I can do something easy yet not exactly correct like make the okButton public and then add an ActionListener:

...

jdialog.setVisible(true);

okButtonPanel.okButton.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent ae){

System.out.println("You pressed the ok button, closing dialog");

jdialog.setVisible(false);

}

});

...

But how do I make it more robust? How do I "listen" to events that happen inother objects and take the appropriate action onmy object?

[1817 byte] By [.drew.a] at [2007-11-27 0:54:39]
# 1

> I add this JPanel to a JDialog. I want this dialog to close whenever the ok button is pressed.

Then you need to write more generic code in the ActionListener. For example you would use:

SwingUtilities.windowForComponent(...)

method to get the JDialog that the button belongs to. Once you have the dialog you just use dialog.dispose() or dialog.setVisible( false );

camickra at 2007-7-11 23:27:08 > top of Java-index,Desktop,Core GUI APIs...