Textfield in panel in frame is initially set to NOT visible; later the program sets it to visible but it doesn't show

StackOverflow https://stackoverflow.com/questions/19556145

  •  01-07-2022
  •  | 
  •  

Question

The text in txDiv0 is supposed to show up when division by 0 is attempled. It is set to NOT visible initially. The code works correctly BUT THE TEXT ONLY SHOWS WHEN I click the frame border as if to make it larger. Making the frame literally one pixel taller makes the field show up.

Code produced by GUIbuilder:

    private javax.swing.JTextField txDiv0;
...
    txDiv0 = new javax.swing.JTextField();
...
    txDiv0.setText("Division by 0 is undefined");  
...
    javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
    jPanel6.setLayout(jPanel6Layout);
    jPanel6Layout.setHorizontalGroup(
      jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(txDiv0, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap())
    );
    jPanel6Layout.setVerticalGroup(
      jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup()
        .addGap(0, 11, Short.MAX_VALUE)
        .addComponent(txDiv0, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
...    
    pack();

And here's how I try to make it show up:

    txDiv0.setVisible(true);
    System.out.println();

(The println is there to show me that the code DID execute.)

The textfield NEVER shows up unless I barely wiggle an edge of the frame.

Was it helpful?

Solution

You will want to call revalidate() and then repaint() on the container that holds your txDiv0 component after changing its visibility. The reason for this is:

  • revalidate() tells the component to have its layout managers re-layout the components it contains. This laying out will cascade through all the layout managers of the components that the current container holds.
  • repaint() suggests to the JVM that the container may have some dirty regions that need to be repainted after components have been removed, added, or shifted around.

As an aside, I strongly urge you to lay the GUI-builder to the side when learning a GUI library, and instead try to create and modify the GUI by hand as this will give you a greater understanding of the underpinnings of the GUI library and will force you to read and study tutorials more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top