简体   繁体   中英

Closing JFrame from JApplet

I'm stuck. I have a JFrame that, upon clicking on a JButton, launches a JApplet that is in another JFrame . What I am wondering is how I can close the JFrame in which the JApplet is in upon clicking on an "Exit" JButton in the JApplet.

Edit:I sliced down my code to show what I mean.

 import javax.swing.JFrame;

 public class Example {


 public static void main(String[] args) {
    Menu frame = new Menu();
    frame.setTitle("Menu");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setResizable(false);
    frame.setVisible(true);

    }
 }

.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Menu extends JFrame{

private JButton jbt=new JButton("Applet");

public Menu(){
    add(jbt);

    ButtonListener listener=new ButtonListener();
    jbt.addActionListener(listener);

}
public static void run(JApplet applet, int width, int height,String title){
    JFrame myFrame = new JFrame();
    myFrame.setTitle(title);
    myFrame.getContentPane().add(applet);
    myFrame.setSize(width, height);
    myFrame.setResizable(true);
    myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    applet.init();
    applet.start();
    myFrame.setVisible(true);
}

class ButtonListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e){
        if (e.getSource()==jbt)
        {
            run(new myApplet(),400,180,"Applet");
        }

    }
 }
}

.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class myApplet extends JApplet{

        private JButton jbtExit=new JButton();

    @Override
    public void init(){
        add(jbtExit);
        jbtExit.addActionListener(new ButtonListener());
    }

    class ButtonListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e){
        if (e.getSource()==jbtExit)
        {
            setVisible(false);
        }

    }
 }

See Closing an Application for some general ideas.

You should be able to use the ExitAction for your Exit button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM