Cutter Cutter - 1 year ago 62
Java Question

Sometimes swing text field appears sometimes it doesn't?

I've got a piece of code that sometimes runs fine and sometimes doesn't. I'm literally not changing anything but sometimes the text field will appear and sometimes it won't appear. How can code possibly run differently every time? It makes no sense to me. I'm reasonably new to java but I certainly didn't think this was possible...

If anyone can help me, could you include the fix, but also why this is happening? Because I'd like to understand the problem fully.

Here is my code:

import javax.swing.*;

public class Window {
JFrame frame;
JPanel panel;

public Window(int x, int y, String t, boolean isHomePage){

int xSize = x;
int ySize = y;
String title = t;

frame = new JFrame();
frame.setSize(xSize, ySize);

panel = new JPanel();

if (isHomePage){


public void homePage(){

JLabel usernameLabel = new JLabel();
usernameLabel.setText("Please enter your username:");

JTextField textbox = new JTextField();



Answer Source

As Reimeus states --

  1. Use a layout manager not null layout. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
  2. Also call setVisible(true) on the JFrame after adding all components to the GUI, not before.

Note that you're confused on how setVisible(true) works. Yes, you're calling it on your sub components, but they've already get their visible property as true by default, and so calling this on the sub components has no effect. Your problem is when you're calling setVisible on the JFrame. You're calling it before adding the JPanel with the text field on it, and so this will cause it to appear occasionally. Prove it for yourself. Minimize and restore your GUI if the texzt field isn't visible, and it should now show.

Myself, if I wanted to swap views as you're trying to do above, I'd use a CardLayout.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download