Close the window using the button

I am currently studying Javato improve myself. I have a program that has a main window, menu and submenu.

I have other windows when I click on my submenus.

One of them is setRates, which

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 this window to close when I click on closeButton.

I created a class for closeButton, actionListener, which:

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 this button, it closes my main window instead of the submenu window. What should I do to fix this problem?

+3
source share
2 answers

, , dispose() . , - , .

: SwingUtilities.getWindowAncestor(...). JButton, ActionEvent, . - ...

public void actionPerformed(ActionEvent e) {
  Object o = e.getSource();
  if (o instanceof JComponent) { 
    JComponent component = (JComponent)o; 
    Window win = SwingUtilities.getWindowAncestor(component);
    win.dispose();
  }
}
  • : , - .
  • , , , ActionListener, , , .
+6

, , . - :

JFrame openedWindow;

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

All Articles