[英]Can't seem to get text entered in a Jtextfield and use that text to replace JLabels when “Submit” button is pressed
[英]Can't add JLabels when button is pressed w/gridbaglayout
我是一個相對較新的程序員,我正在嘗試通過制作一個非常基本的游戲來測試我對 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 程序員眼中犯了一個簡單的錯誤,我深表歉意。 謝謝!
你需要驗證();
public void clearPanel() {
panel.removeAll();
panel.validate();
panel.repaint();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.