1

I'm writing a program using Swing that involves a form. When the form is submitted, I have a function that validates it, and any invalid fields are supposed to be highlighted in red to be corrected, then changed back to the default border once valid.

Currently, I am using the following method to get the default JTextField border.

private Border defaultBorder = new JTextField().getBorder();

Is there a way to do this without creating an unnecessary object?

More importantly, how do I change the color of the border without affecting its other properties?

  • 1
    `UIManager.getBorder("Textfield.border")` depending on the look and feel. You could also use something like `JLayer` to paint onto your UI, [for example](http://stackoverflow.com/questions/25274566/how-can-i-change-the-highlight-color-of-a-focused-jcombobox/25276658#25276658) – MadProgrammer Jan 21 '15 at 09:29
  • As suggested in the relevant [API](http://docs.oracle.com/javase/8/docs/api/javax/swing/JComponent.html#setBorder-javax.swing.border.Border-). – trashgod Jan 21 '15 at 09:58

1 Answers1

1

I'd add the text field to a panel and set the border of the panel.

That way, we can leave the border of the text field untouched and it will still have the appropriate border for that PLAF and situation (focused etc.).

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433