删除/替换JFrame窗口?

时间:2016-06-02 18:36:28

标签: java jframe jpanel

如果用户输入字母“N”,我想替换JFrame(包含JPanel)。

我当前的代码只是添加了一个新的JFrame,但没有删除前一个。

这是我的Frame.java课程:

public class Frame extends JFrame {
    public Frame() {
        add(new Panel());
        pack();
    }

    public static void main(String[] args) {
        JFrame frame = new Frame();
        frame.setVisible(true);
    }
}

这是我的Panel.java课程:

public class Panel extends JPanel implements ActionListener {

    public Panel() {
        setPreferredSize(new Dimension(1000, 1000));
        setFocusable(true);

        addKeyListener(new PanelKeyListener());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Paint things
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }

    class PanelKeyListener implements KeyListener {

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();

            switch (keyCode) {
                case KeyEvent.VK_N:
                    JFrame frame = new Frame();
                    frame.setVisible(true);
                    break;
             }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果您真的想要替换JFrame,可以打开一个新的JFrame并使用以下命令关闭它:

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

或者通过:

frame.setVisible(false); 
frame.dispose(); 

但是,更换JFrame非常奇怪。通常,我们更改框架的内容(使用setContentPanel)而不是框架本身:)

frame.setContentPanel(new OtherPanel())

Personnaly,我会将您的代码更改为:

public class Frame extends JFrame {
    public static void main(String[] args) {
        JFrame frame = new Frame();
        frame.setContentPane(new MyPanel(frame)); 
        frame.setVisible(true);
    }
}

public class MyPanel extends JPanel implements ActionListener {
    private Frame refFrame; 
    public MyPanel(Frame frame) {
        this.refFrame = frame; 

        setPreferredSize(new Dimension(1000, 1000));
        setFocusable(true);

        addKeyListener(new PanelKeyListener());
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        // Paint things
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
    }

    class PanelKeyListener implements KeyListener {

        @Override
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();

            switch (keyCode) {
                case KeyEvent.VK_N:
                    refFrame.setContentPane(new OtherPanel()); 
                    break;
             }
        }
    }
}