Yeliz Il
Yeliz Il

Reputation: 49

Closing a Window with Button

I am currently studying Java to improve myself. I have a program which has a main window, menu and submenus.

I have other windows on when I click on my submenus.

One of them is setRates which is

public SetMyRates(){
    JPanel dataPanel = new JPanel(new GridLayout(2, 2, 12, 6));
    dataPanel.add(setTLLabel);
    dataPanel.add(setDollarsLabel);
    dataPanel.add(setTLField);
    dataPanel.add(setDollarsField);
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(closeButton);
    buttonPanel.add(setTLButton);
    buttonPanel.add(setDollarsButton);
    Container container = this.getContentPane();
    container.add(dataPanel, BorderLayout.CENTER);
    container.add(buttonPanel, BorderLayout.SOUTH);
    setTLButton.addActionListener(new SetTL());
    setDollarsButton.addActionListener(new SetDollars());
    closeButton.addActionListener(new closeFrame());
    dataPanel.setVisible(true);
    pack();
}

and I want that window to close when I click on my closeButton.

I made a class for closeButton, actionListener which is:

private class closeFrame implements ActionListener{
    public void actionPerformed(ActionEvent e){
       try{
          dispose();
       }
       catch(Exception ex){
          JOptionPane.showMessageDialog(null, "Please enter correct Rate.");
       }
    }
}

But when I click that button, it closes my main window instead of my submenus window. What should I exactly do to fix the problem?

Upvotes: 3

Views: 340

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You need to get a reference to the Window that you want to close and call dispose() directly on that reference. How you do this will depend on the details of your program -- information that we're currently not privy to.

Edit: one way to get that reference is via SwingUtilities.getWindowAncestor(...). Pass in the JButton reference returned from your ActionEvent object and call dispose on it. Something like...

public void actionPerformed(ActionEvent e) {
  Object o = e.getSource();
  if (o instanceof JComponent) { 
    JComponent component = (JComponent)o; 
    Window win = SwingUtilities.getWindowAncestor(component);
    win.dispose();
  }
}
  • caveat: code neither compiled nor run nor tested in any way.
  • Also note that for this to work, the component that holds and activates the ActionListener has to reside on the Window that you wish to close, else this won't work.

Upvotes: 6

Boro
Boro

Reputation: 7943

From what I think you could easily when opening an another window just store a reference to it and use it inside the action listener. Something along these lines:

JFrame openedWindow;

//inside the listener
if(openedWindow)
   openedWindow.dispose();
else dispose();

Upvotes: 4

Related Questions