我是一个相对较新的程序员,我试图通过制作一个非常基础的游戏来测试我对JFrame和Java GUI的了解。目前,我正在主菜单上。我正在使用GridBagLayout来布局屏幕上的所有组件。当用户单击指示按钮时,应该清除面板并添加一个新的JLabel。我已经成功编写了一种清除面板的方法,但是无法添加新的JLabel。这是我当前的代码:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
GridBagConstraints c = new GridBagConstraints();
int WIDTH = 500;
int HEIGHT = 500;
public static void main(String[] args) {
Main game = new Main();
game.window();
}
public void window() {
// window builder
frame.setSize(WIDTH, HEIGHT);
frame.setVisible(true);
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setTitle("Spaceship War");
frame.setLocationRelativeTo(null);
//GUI layout
panel.setLayout(new GridBagLayout());
JButton playButton = new JButton("Play!");
playButton.addActionListener(new playListener());
c.ipadx = 50;
c.ipady = 50;
c.gridx = 0;
c.gridy = 0;
panel.add(playButton, c);
JButton instructionsButton = new JButton("Instructions");
instructionsButton.addActionListener(new instructionsListener());
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.anchor = GridBagConstraints.PAGE_END;
c.gridy = 1;
panel.add(instructionsButton, c);
JButton quitButton = new JButton("Quit");
quitButton.addActionListener(new quitListener());
c.insets = new Insets(10,0,0,0);
c.gridx = 0;
c.gridy = 2;
panel.add(quitButton, c);
frame.add(panel);
}
public void clearPanel() {
panel.removeAll();
panel.repaint();
}
public void instructionsScreen() {
clearPanel();
JPanel instructionsPanel = new JPanel();
JLabel instructionsLabel = new JLabel("test");
instructionsPanel.add(instructionsLabel);
frame.add(instructionsPanel);
}
// event listener classes
class playListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Play button pressed!");
clearPanel();
}
}
class instructionsListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Instructions button pressed!");
clearPanel();
instructionsScreen();
}
}
class quitListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("Quit button pressed!");
System.out.println("Exiting...");
System.exit(0);
}
}
}
如果我在经验丰富的Java程序员眼中犯了一个简单的错误,我深表歉意。谢谢!
您需要validate();
public void clearPanel() {
panel.removeAll();
panel.validate();
panel.repaint();
}