6

The code is like this:

JTextField txt = new JTextField();
txt.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));

However the text field is ignoring my call to setBorder. No changes whatsoever.

I were to replace it with a JLabel (for instance)

JLabel txt = new JLabel();
txt.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.red));

I would see the red border.

Can anybody tell me why? Or even better explain to me how to add a border in the JTextField?

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Markus V.
  • 347
  • 2
  • 4
  • 6
  • That "should" work. Are you using JTextField or a custom class that extends JTextField? What else are you doing to the JTextField? Are you setting the border elsewhere? – Pace Feb 17 '10 at 14:48
  • It takes two seconds to prove whether it does or it does not. Honest. Either you take my word or write a little test and see for your self. Anyway other bits of info are: The uimanager is set on Windows UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); and I don't work on a class that extends JTextField. I am using the JTextField itself. – Markus V. Feb 17 '10 at 14:52
  • "to prove" Behaviour is going to depend upon PL&F, version of PL&F, platform, version of platform and possibly configuration. Not so easy to prove. It'd be easier to try if you included a should compilable example. – Tom Hawtin - tackline Feb 17 '10 at 15:18
  • And taking just a little bit of care formatting the question would help. Particularly if you are suggesting people write test programs themselves. – Tom Hawtin - tackline Feb 17 '10 at 15:20
  • I tested it and it worked using "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"! (Windows XP, Java 1.6.0_16) – user85421 Feb 17 '10 at 15:27

1 Answers1

6

Check out this explanation/recommendation from the Java API

In general, when you want to set a border on a standard Swing component other than JPanel or JLabel, we recommend that you put the component in a JPanel and set the border on the JPanel.

So... you should nest your JTextField in a JPanel or JLabel, and put the border on the JPanel or JLabel. Voila!

Timothy
  • 2,457
  • 19
  • 15