Swing JTextField how to remove the border?

Viewed 65600

Is there anyway to remove a border in a JTextField?

txt = new JTextField();
txt.setBorder(null);   // <-- this has no effect.

I would really want it to look like a JLabel - but I still need it to be a JTextField because I want people to be able highlight it.

7 Answers

From an answer to your previous question you know that some PL&Fs may clobber the border.

The obvious solution is to therefore override the setBorder method that the PL&F is calling, and discard the change.

JTextField text = new JTextField() {
    @Override public void setBorder(Border border) {
        // No!
    }
};

Try setting it to BorderFactory.createEmptyBorder() instead of null. Sometimes this "does the trick" because setting it to null actually has a different meaning.

If that does not work, it is possible that the look and feel you are using is overriding something. Are you using the default or something custom?

You can simply

textField.setBorder(null);

or

textField.setBorder(new EmptyBorder(0, 0, 0, 0))

The only way to make it works in ALL circumstances is the following setting:

setBorder (BorderFactory.createLineBorder (new Color (0, 0, 0, 0), 2));

otherwise (when you have null background of the parent container) you will see the "I" cursor remaining forever at the left edge of your JTextField. (Simply make some tests for different border thickness and observe quite strange way the JTextField places the cursor when you activate it first time.)

Alternatively you can set:

setBorder (BorderFactory.createLineBorder (getBackground (), 2));

but you will obtain the field opticaly larger by 2 pixels in all four directions. If you don't specify the border thickness, you will see the cursor BETWEEN this border and the field remaining forever.

Related