JTextField正在消除我的JPanels

时间:2013-12-30 16:43:23

标签: java swing jframe jpanel jtextfield

我正在尝试了解有关创建更多动态GUI的更多信息。我希望添加具有不同内容的不同面板,当您按下一个主面板上的按钮时,它会更改相邻的面板。我添加了两个面板和一些按钮,当我测试程序时,它显示正确。问题是当我添加JTextField(或JTextArea)时,面板是空白的,没有按钮。奇怪的是我没有将JTextField添加到任何一个面板中。我只创建了一个全局变量。如果我发表评论,程序运行正常。我错过了一些非常简单的事吗?

以下是具有gameWindow

JTextField
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();
}

}

2 个答案:

答案 0 :(得分:4)

setVisible应该在最后。您当前将可见设置为true,然后添加面板。

mainwindow.setVisible(true);
mainwindow.add(new gameWindow());

setVisible放在setDeaultCLoseOperation

之后的末尾

答案 1 :(得分:1)

我不完全确定为什么会这样做,也许其他人可以解释。

我所知道的是,我通常会致电pack()这似乎会让您的问题消失。

private static void mainWindow(){
    final RPGCreator mainwindow = new RPGCreator();
    mainwindow.setMinimumSize(new Dimension(1200, 800));
    mainwindow.setResizable(false);
    mainwindow.setTitle("RPG Creator");
    mainwindow.setVisible(true);
    mainwindow.add(new gameWindow());
    mainwindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainwindow.pack(); //This usually goes after you've added all of your components
    mainwindow.setLocationRelativeTo(null);
}

一些注意事项:

  1. 我不得不改为mainwindow.setMinimumSize(new Dimension(1200, 800));以避免框架看起来被压扁。虽然我通常会让布局经理处理事情的大小。
  2. 致电setLocationRelativeTo(null)后致电pack(),以使其具有所需效果。再次不确定为什么,但我通过一些困难了解到了。