TextBox not displaying on frame until the frame is

2019-09-17 21:51发布

问题:

I am trying to create a login page. I wrote code for two textboxes and one button. One textbox next to Username and other one next to Password. One "Sign In" button below. But I am not sure why the textbox's and button are not shown on my output. I only get the Username and password label's on my ouput screen.

Strange thing is whenever I stretch my output frame, (I mean either pulling the screen horizontally or vertically) the two textboxes and the button shows up.

Please check my code and let me know what's wrong. I was trying to put pictures to make easier to understand but I do not have enough reputation. Please help.

import javax.swing.*;
import java.awt.*;

public class HomeScreen{

public static void main(String args[]){

JFrame frame = new JFrame("Medical Store");
frame.setVisible(true);
frame.setSize(600,400);
JPanel panel = new JPanel(new GridBagLayout());
frame.getContentPane().add(panel, BorderLayout.NORTH);

GridBagConstraints c = new GridBagConstraints();

JLabel label1 = new JLabel("Username");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,10,10);
panel.add(label1,c);

JLabel label2 = new JLabel("Password");
c.gridx = 0;
c.gridy = 1;    
panel.add(label2,c);

JTextField textbox1 = new JTextField(10);
c.gridx = 1;
c.gridy = 1;
panel.add(textbox1,c);

JTextField textbox2 = new JTextField(10);
c.gridx = 2;
c.gridy = 1;
panel.add(textbox2,c);

JButton button1 = new JButton("Sign In");
c.gridx = 1;
c.gridy = 2;
panel.add(button1,c);

}   
}

回答1:

You're calling setVisible(true) before adding all components, and so your GUI is doing just that, drawing itself before components are added.

JFrame frame = new JFrame("Medical Store");
frame.setVisible(true);

// all components added here

Solution: make the setVisible(true) call at the end after adding all components.

JFrame frame = new JFrame("Medical Store");

// all components added here

frame.setVisible(true);

Now all components should be visualized.

Other quibbles:

  • Avoid calling setSize(...) on anything. Instead let the layout managers and component preferred sizes do that for you.
  • Call pack() on the JFrame just prior to setting it visible so that the above will happen.