Hi I prepared one swing frame in which I placed two text fields. Is there any way to get one side(i.e., right bordered line) of the jtextfield colored? Please suggest. I checked many things, but I couldn't find.Thanks in advance.
Asked
Active
Viewed 3,658 times
3 Answers
9
In the example below I added a left side border of 5 pixels:
JTextField jtf = new JTextField();
jtf.setBorder(BorderFactory.createMatteBorder(0, 5, 0, 0, Color.BLACK));
This is a right side border:
jtf.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 5, Color.BLACK));
I hope this is what you are after

Timmo
- 3,142
- 4
- 26
- 43
9
I would add a Border to the text field, something along the lines of:
Border oldBorder = jTextField.getBorder();
Border redBorder = BorderFactory.createMatteBorder(0, 0, 0, 5, Color.RED);
Border newBorder = BorderFactory.createCompoundBorder(redBorder, oldBorder);
jTextField.setBorder(newBorder);
This approach keeps the old border and wraps it inside your red (partial) border.

Jacob Raihle
- 3,720
- 18
- 34
-
cleaner than the other answer, although I don't think that OP needs to keep the original border. – brimborium Aug 13 '12 at 13:41
-
Thank you so much Jacob. As I apply only the matteBorder, the textfield is losing it's original border too and displaying only one sided red border and looking like a line rather than text field. But your answer avoided that scenario. – Kanth Aug 13 '12 at 14:17
4
You could create your own CustomBorder
class by extending from the Border
class and creating your own custom border for your component. Set it by calling setBorder()
on your Component
's instance something like:
class MyBorder implements Border {
@Override
public void paintBorder(Component cmpnt, Graphics grphcs, int x, int y, int width, int height) {
//draw your border here
}
@Override
public Insets getBorderInsets(Component cmpnt) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isBorderOpaque() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Reference:

nIcE cOw
- 24,468
- 7
- 50
- 143

David Kroukamp
- 36,155
- 13
- 81
- 138
-
1Why the **Question Mark** at the very end ? This is not making any sense. Though +1 for Custom Border :-) – nIcE cOw Aug 13 '12 at 13:36
-
-
1While providing snippets, much wise would be to use proper names instead of **i/i1/i2/i3**, better to use, **int x, int y, int width, int height**, so that it conveys the message, without more thoughts :-) – nIcE cOw Aug 13 '12 at 13:41
-
1