简体   繁体   English

Java从另一个类处理JFrame窗口

[英]Java Disposing JFrame window from another class

A class Main has main method in which JFrame is constructed.类 Main 具有构造 JFrame 的 main 方法。 And class MainView has panels and buttons which are appended on the JFrame.并且类 MainView 具有附加在 JFrame 上的面板和按钮。

What I need to do is disposing JFrame window by clicking a certain button.我需要做的是通过单击某个按钮来处理 JFrame 窗口。

I have tried various ways which I have found from here, Stackoverflow.我尝试了从这里找到的各种方法,Stackoverflow。 But no solution so far.但目前没有解决办法。

public final class Main {

static JFrame frame = null;

public static void main(String[] args) throws IOException {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {

            try {
                frame = new MainView("Blackjack 2017");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(650, 450);
            frame.setVisible(true);
        }
    });


}
}

From

public class MainView extends JFrame implements ActionListener {

private static final long serialVersionUID = 4728244239185625080L;
private Dealer dealer;
private User user;
private ControlPanel controlPanel;
public static Container c;

public MainView() {

}

public MainView(String title) throws IOException {

    super(title);

    dealer = new Dealer();
    user = new User();

    System.out.println(title + " frame made");

    controlPanel = new ControlPanel();
    controlPanel.setControlPanel();

    c = getContentPane();
    c.add(controlPanel);

    controlPanel.getPlayBtn().addActionListener(this);
    controlPanel.getExitBtn().addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Play")) {
        System.out.println("play clicked");
        c.removeAll();
        c.add(playPanel);
        c.validate();

    } else if (e.getActionCommand().equals("Exit")) {


    }

Check out Closing an Application for some basics about closing a frame (or dialog).查看关闭应用程序以了解有关关闭框架(或对话框)的一些基础知识。

You can just use The ExitAction class, which is a generic Action that can be added to any button (or menu item) and will act as if the user clicked on the close button of the window.您可以只使用ExitAction类,它是一个通用Action ,可以添加到任何按钮(或菜单项),并且就像用户单击了窗口的关闭按钮一样。

The code works by dispatching a windowClosing event to the window.该代码通过将windowClosing事件分派到窗口来工作。 So it assumes you have invoked the setDefaultCloseOperation(...) for the window.所以它假设您已经为窗口调用了setDefaultCloseOperation(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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