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?
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…