我正在构建的游戏涉及在调用startGame()
时单击开始按钮后切换面板。单击按钮后程序会冻结,什么都不做。
以下是代码段:
public class ArtilleryGame extends JFrame {
private static final long serialVersionUID = 1L;
//TODO: fix clouds from updating with background
static StartPanel startPanel = new StartPanel();
public ArtilleryGame() throws InterruptedException
{
setSize(898,685);
setLocationRelativeTo(null);
setTitle("Tank Game");
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
URL sound = this.getClass().getResource("Sounds/Intro_Screen.wav");
AudioClip drop = Applet.newAudioClip(sound);
drop.loop();
drop.play();
add(startPanel);
//add(new GamePanel());
buttons();
setVisible(true);
}
private void buttons()
{
URL startURL = this.getClass().getResource("imgg/StartBtn.png");
BufferedImage startI = new BufferedImage(170, 62, BufferedImage.TYPE_INT_RGB);
try
{
startI = ImageIO.read(startURL);
} catch (IOException e)
{
e.printStackTrace();
}
ImageIcon startImg = new ImageIcon(startI);
JButton startBtn = new JButton(startImg);
startBtn.setSize(170, 62);
startBtn.setBorder(BorderFactory.createEmptyBorder());
startBtn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
startGame();
}
});
startBtn.setLocation(365, 310);
StartPanel.background.add(startBtn);
}
public void startGame()
{
remove(startPanel);
add(new GamePanel());
}
public static void displayCredits()
{
JOptionPane.showMessageDialog(null, new CreditsPanel(), "Tank Game", JOptionPane.PLAIN_MESSAGE);
}
public static void main(String[] args) throws InterruptedException
{
new ArtilleryGame();
//displayCredits();
}
}
答案 0 :(得分:0)
使用CardLayout
。 CardLayout
允许您轻松交换面板。
阅读How to Use CardLayout上Swing教程中的部分,了解更多信息和工作示例。