Search code examples
javaswingjframejpaneljtextfield

JTextField is blanking out my JPanels


I am attempting to learn more about creating more dynamic GUI's. I am hoping to add different panels with different content and as you press buttons on one main panel, it changes the adjacent panels. I have added two panels and some buttons and when I test the program, it displays correctly. The problem is when I add a JTextField (or JTextArea) the panels are blank and there are no buttons. The strange thing is I haven't added the JTextField to either panel. I have only created a global variable. If I comment it out, the program runs correctly. Am I missing something very simple?

Here is the gameWindow class that has the 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);
    }

}

Here is main

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

}

Solution

  • setVisible should go at the end. You're currently setting visible to true, and then adding a panel.

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

    Put setVisible at the end after setDeaultCLoseOperation