Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

actionPerformed to close dialog

 
Simon Lai
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an external action listener class for a button.
how do I use make the button close the dialog box on which the button is located?
 
Daniel Searson
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the constructor of your ActionListener, add a parameter for the "owner dialog". ie:
public MyActionListener(JDialog ownerDialog)
Then when the button is clicked, call ownerDialog.dispose()
Hope that helps.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, use the getSource() method of ActionEvent, to get the Button ( or other Component ) that caused this ActionEvent. Then, use the getParent() method of the Button ( inherited from Component ) to return the container that this Button is in... you may want to put this in a loop until you can't get a parent anymore... if a Button is in deeply nested Panels, I belive this method will just return the panel that the button is in...

So, you will end up with something like the code below...
(Warning! This code has not been tested...)

HTH,
-Nate
 
YY MM
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
tested code is recommended as followed

//close the Dialog
if( e.getSource() instanceof JButton )
// Make sure this event was launched from a Button.
{
Container c = ((JButton)(e.getSource())).getParent();
// get the container for this button.
while( (c.getParent() != null)&&(!(c instanceof JDialog)) )
{
c = c.getParent();
}
// loop until you get the top level frame/dialog...
// you may want to play with this some... I know that
// problems may arise in Applets, since the top level
// frame is the browser, and Dialogs may present a
// problem too, since Frames may be their parents...
// experiment with calls...
if( c instanceof JDialog )
// If the top level container you finally found was a
// dialog...
{
JDialog d = ( JDialog )c;
// Now you have a reference to the Dialog, and can
// manipulate it however you want...
d.dispose();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic