Dispose a JFrame on button click from another JFra

2019-02-28 06:33发布

问题:

As many probably know, I am a complete Java newbie. I have already attempted to research this (by reading other posts on StackOverflow, Googling and asking a friend who is less of a java newbie) but I can't figure it out. The answer is probably clear and easy but I am blind to it. I am attempting to dispose a JFrame from a different frame.

My application is supposed to work as follows:

  • Frame X has a button, when pressed: spawns frame Y
  • Frame Y has a button, when pressed: spawns frame Z
  • Frame Z has a button, when pressed: performs method from frame Y before disposing frame Y and itself.

Getting frame Z to dispose frame Y is where most of my issues are. Any help is greatly appreciated. Ideally help will be phrased in such a way that even a baby could understand (because that is my level of Java comprehension).

I know many will think this is a duplicate question of either this question or this other question. I believe it is not a duplicate question because I have read both and have not understood how to resolve my own problem.

回答1:

  • Frame Z has a button, when pressed: performs method from frame Y before disposing frame Y and itself.

Frame Y and frame Z should be modal dialogs (at least Z should be, probably also Y).

When dialog Y goes to open dialog Z (we'll call it dialogZ) the code should go something like this:

DialogZ dialogZ = new DialogZ(..);
dialogZ.setVisible(true);
this.setVisible(false); // at this point, dialogZ will have been closed

See How to Use Modality in Dialogs for details and example code.

(Frame Z) … performs method from frame Y

Frame Y and Frame Z should probably not extend any class. Instead they should be instance variables that are used as needed.



回答2:

you could hold a reference to the other jframe in another frame. this class could look like this:

The constructor takes a jframe, which should be controlled from this jframe.

class YourFrame {
   public YourFrame(JFrame controlFrame){
       //build the frame and a button, which action listener calls controlFrame.setVisible(false);
       JFrame f = new JFrame();
       f.setSize(800, 600);
       JPanel content = new JPanel();
       JButton button = new JButton();
       button.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e){
               controlFrame.setVisible(false);
            }
       }
       content.add(button); 
       f.add(content);
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       f.setVisible(true);
   }
}