I have a JFrame , and to one of its button 'done', I wish to add an ability to close the window...ie on clicking done this window should close.

jen

Recommended Answers

All 5 Replies

Since your using swing it's easy:


In the action performed method, just check which button was clicked and then add this line of code:

System.exit(0);

for example:

public void actionPerformed(ActionEvent ae)
{
       if (ae.getSource() == doneButton)
       {
               System.exit(0);
       }
}

jeni

Remember that java matches on object references so the reference to doneButton should be the name you gave to the button object when you made it.

jeni

Remember that java matches on object references so the reference to doneButton should be the name you gave to the button object when you made it.

Not really. There are two ways of doing this:

JButton doneButton = new JButton("Done");


if (ae.getSource() == doneButton)
{
}


or 

if (ae.getActionCommand().equals("Done"))
{
}

You can compare the actual object itself, or the name of it.

Well!! Thanks every one for their reply.

I has actually tried system.exit(0), but that closes the complete application. However looking through the API I realised that I could use dispose()..i tried that and it works fine.

Thanks every one once again

I personally like making a button a listener of itself instead of having if statements determining what is suppose to happen when a specific button is pressed...

public class ExtendedJButton extends JButton implements ActionListener
{
	public ExtendedJButton()
	{
		init();
	}
	
	private void init()
	{
		addActionListener(this);
	}
	
	public void actionPerformed(ActionEvent event)
	{
		System.out.println("Override this method with an anonymous inner clas");
	}
}

Then to use this class do the following when creating the button...

JButton jButton = new ExtendedJButton()
{
  public void actionPerformed(ActionEvent event)
  {
    System.out.println("I'm suppose to do something exciting here...");
  }
};

Some people might say that this is over kill, but i think a button should know what it is suppose to do and what if a panel has over a hundered buttons on it? Do you really want to have a 100 case if statement?

Regards,

Nate

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.