调用getContentPane()后,JFrame冻结.removeAll()

时间:2013-11-12 11:23:19

标签: java swing jframe minesweeper

这个问题的标题不言而喻。我正在使用JFrame克隆扫雷并刚刚完成了玩家选择游戏大小的起始屏幕。单击一个按钮时,Frame应该为游戏屏幕做好准备。当我单击按钮时,按钮保持“按下”状态,JFrame冻结,我必须将其关闭。我做错了什么?

代码:

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


public class Minesweeper extends JFrame implements ActionListener{

    JLabel starttitle;
    ButtonObject[] gamefield;
    JFrame frame;
    JPanel startscreen;
    JPanel gamescreen;
    int gamesize;
    JButton ten;
    JButton tfive;
    JButton fifty;

    GridLayout layout; 



    public Minesweeper()
    {
        frame = new JFrame("Minesweeper");
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);;
        startscreen = new JPanel();
        startScreen();
    }

    public void startScreen()
    {
        ten = new JButton("10 x 10");
        tfive = new JButton("25 x 25");
        fifty = new JButton("50 x 50");
        starttitle = new JLabel("Welcome to minesweeper. Click a game size to begin.");
        frame.add(startscreen);
        startscreen.add(starttitle);
        startscreen.add(ten);
        startscreen.add(tfive);
        startscreen.add(fifty);
        ten.addActionListener(this);
        tfive.addActionListener(this);
        fifty.addActionListener(this);
    }
    public void gameScreen()
    {
        frame.getContentPane().removeAll();//freezes JFrame
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==ten)
        {
            gamesize = 10;

            gameScreen();
        }
        else if(e.getSource()==tfive)
        {
            gamesize = 25;

            gameScreen();
        }
        else if(e.getSource()==fifty)
        {
            gamesize = 50;

            gameScreen();
        }
        else
        {
            System.out.println("Fatal error");
        }

    }
    public static void main(String[] args)
    {
        new Minesweeper();
    }
}

3 个答案:

答案 0 :(得分:5)

它不会冻结,调用框架的repaint()方法,所有组件都会清除。

只需在actionPerformed()中添加下一行:

 frame.repaint();

答案 1 :(得分:2)

就像这样..

    public void gameScreen()
    {
        frame.getContentPane().removeAll();
        frame.repaint();
    }

答案 2 :(得分:2)

  • JFrame的默认LayoutManagerBorderlayout

  • 对已经可见的Swing GUI(添加,删除,调整大小,修改)的所有更改都必须通知已使用的LayoutManager

  • JFrame的标准通知符为frame.(re*)validateframe.repaint()**

    1. * - 在Java7及更新版本中

    2. ** - 并非在所有情况下都需要(JTextComponentsJFrame.pack(),e.i。),默认情况下也最好使用此代码行