gpt4 book ai didi

java - JFrame 在调用 getContentPane().removeAll() 后卡住

转载 作者:行者123 更新时间:2023-11-29 10:02:29 32 4
gpt4 key购买 nike

这个问题的标题不言自明。我正在使用 JFrame 制作扫雷的克隆,并且刚刚完成玩家选择游戏大小的起始屏幕。单击按钮时,框架应该会为游戏屏幕做好准备。当我单击一个按钮时,该按钮仍处于“按下”状态并且 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();
}
}

最佳答案

它不会卡住,调用你的框架的repaint()方法,所有的组件都会被清除。

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

 frame.repaint();

关于java - JFrame 在调用 getContentPane().removeAll() 后卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19927824/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com