JTextField does not appear in JPanel at startup

JTextField is there because when I move the mouse where it should be the mouse pointer changes to the cursor and then when I click it appears. But this is invisible at startup. What am I missing?

 public class JavaSwingTextfield extends JFrame { private static final long serialVersionUID = 1L; JTextField myTextField; public JavaSwingTextfield(){ /***** JFrame setup *****/ // Set the size of the window setSize(600,600); // Make the application close when the X is clicked on the window setDefaultCloseOperation(EXIT_ON_CLOSE); // Makes the JFrame visible to the user setVisible(true); /***** JFrame setup END *****/ /***** JButton setup *****/ // Create a JLabel and set its label to "Start" myTextField = new JTextField("Start"); // Set the label size myTextField.setSize(100, 50); // Put the label in a certain spot myTextField.setLocation(200, 50); // Set a font type for the label //Font myFont = new Font("Serif", Font.BOLD, 24); //myTextField.setFont(myFont); // Add the label to the JFrame add(myTextField); /***** JButton setup END *****/ } /***** The main method *****/ public static void main(String[] args){ new JavaSwingTextfield(); } } 
+4
source share
2 answers
  • Use Event Dispatch Thread to create GUI components.
  • Do not call setVisible(..) before all components have been added to the JFrame (this code snippet above shows the actual +1 error for @Clark)
  • Do not JFrame class JFrame
  • Do not call setSize(..) , but just call JFrame#pack() before setting the JFrame visible
  • Don't call setSize() on a JTextField rather look at its constructor: JTextField(String text,int columns)
  • Use the appropriate LayoutManager s, see a few examples here: Visual Guide for LayoutManager Managers

Here is an example I made (basically your patch code):

 import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class JavaSwingTextfield { private JTextField myTextField;  public JavaSwingTextfield() {    JFrame frame = new JFrame();    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        myTextField = new JTextField("Start");        // Add the label to the JFrame    frame.add(myTextField);        //pack frame to component preferred sizes    frame.pack();    frame.setVisible(true);  }  public static void main(String[] args) {    //Create UI on EDT    SwingUtilities.invokeLater(new Runnable() {      @Override      public void run() {        new JavaSwingTextfield();      }    });  } } 
+11
source

You add a JTextfield to the JFrame AFTER that made the JFrame visible. Just add JTextfield before you JTextfield started.

+4
source

Source: https://habr.com/ru/post/1444036/


All Articles