Search code examples
javaswingjtextfield

JTextBox is not shown in JFrame until its clicked. Why?


I am making a program and I need to make a JTextField in my JPanel that is in my JFrame. Everything is set to visible. I Can see JLabel in the same JPanel but not my JTextField.

When I launch code below my JTextField is showing only when clicked. When I cross the cursor over it it changes to I know that it is there. But it is like my JFrame background colour.

import java.awt.Dimension;
import javax.swing.JTextField;

public class HomeSourceTextBox extends JTextField {

private static final long serialVersionUID = -3387184252168604673L;
Dimension d = new Dimension(600, 20);

public HomeSourceTextBox() {
    setSize(d);
    setEnabled(true);
    setText("Text");

    setVisible(true);
   }
}

Solution

  • I'm not sure what you are doing but I think you are trying to make JTextField longer.

    To give your JTextField a default amount of columns use JTextField(int columns) constructor like so:

    JTextField jtf=new JTextField(10);
    

    And as others have suggested please do post an SSCCE so we can see specific problems.

    As a general note though its always better to override get|Minimum|Maximum| Preferred |Size or set|Minimum|Maximum| Preferred |Size,so that LayoutManagers cant change the size (if you are not using a Layout I highly suggest you do though).

    I prefer the getPreferredSize() and the docs agree - JTextField docs

    getPreferredSize()

    Returns the preferred size Dimensions needed for this TextField. If a non-zero number of columns has been set, the width is set to the columns multiplied by the column width.