我正在尝试了解更多关于创建更多动态 GUI 的信息。我希望添加具有不同内容的不同面板,当您按下一个主面板上的按钮时,它会更改相邻的面板。我添加了两个面板和一些按钮,当我测试程序时,它显示正确。问题是当我添加 JTextField
(或 JTextArea
)时,面板是空白的并且没有按钮。奇怪的是我还没有将 JTextField
添加到任一面板。我只创建了一个全局变量。如果我将其注释掉,程序将正确运行。我错过了一些非常简单的东西吗?
这是具有 JTextField
gameWindow
类
package rpgcreator;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
class gameWindow extends JPanel {
JPanel startWindowPanel;
JPanel settingsPanel;
JPanel characterPanel;
JPanel scenarioPanel;
JPanel mapPanel;
JButton CharacterButton = new JButton("Create your character");
JButton StoryButton = new JButton("Choose your Story line");
JButton MapButton = new JButton("Choose your World");
//JTextField nameField = new JTextField(15); //comment or uncomment to see issue
public gameWindow() {
setLayout(new GridLayout(0,2,5,0));
startWindowPanel = new JPanel(new FlowLayout());
settingsPanel = new JPanel(new GridLayout(2,1));
startWindowPanel.setBackground(Color.blue);
settingsPanel.setBackground(Color.black);
startWindowPanel.add(MapButton);
startWindowPanel.add(StoryButton);
startWindowPanel.add(CharacterButton);
add(startWindowPanel);
add(settingsPanel);
}
}
这是主要的
package rpgcreator;
import javax.swing.JFrame;
public class RPGCreator extends JFrame{
private static void mainWindow(){
RPGCreator mainwindow = new RPGCreator();
mainwindow.setSize(1200, 800);
mainwindow.setResizable(false);
mainwindow.setLocationRelativeTo(null);
mainwindow.setTitle("RPG Creator");
mainwindow.setVisible(true);
mainwindow.add(new gameWindow());
mainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO code application logic here
mainWindow();
}
}
最佳答案
setVisible
应该放在最后。您当前正在将可见设置为 true,然后添加一个面板。
mainwindow.setVisible(true);
mainwindow.add(new gameWindow());
将setVisible
放在setDeaultCLoseOperation
之后
关于java - JTextField 正在清空我的 JPanels,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20843730/