Changing Border Color of AWT TextField
Asked Answered
T

5

13

In AWT application I need to set border color of TextField.

In JTextField, I know that we do can do the following

JTextField tf = new JTextField();
tf.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));

But setBorder() method is not availiable in awt TextField. Is there any workaround for this problem?

Terbecki answered 28/9, 2011 at 11:5 Comment(0)
C
9

The AWT TextField does not support borders, as you've found. You could emulate a border by putting the text field inside a Panel that's just slightly larger than the textfield and changing the background color of the panel.

Carbonari answered 28/9, 2011 at 11:26 Comment(2)
Thanks but the TextFields have default gray shade border slightyly on the inner side of textbox..I guess i wont be able to get rid of that ?Terbecki
+1 I was going to suggest overriding paint(), but this looks easier.Secondrate
S
3
tf.setBorder(new LineBorder(Color.red,1));
//new LineBorder(color,width);
Schismatic answered 28/10, 2018 at 9:32 Comment(1)
Please add some explanation. It is a bad practice to put only a fragment of code as an answer.Sowens
S
2

For compatibility with look & feel variations, the setBorder() API recommends the following: "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."

Addendum: While this suggests an approach, it is irrelevant to a pure AWT application.

Secondrate answered 28/9, 2011 at 14:10 Comment(1)
The AWT TextField does not inherit from JComponent.Carbonari
B
2
tf.setBorder(new LineBorder(Color.red,1));
//new LineBorder(color,width);

Because the method is overloaded you can define the Color, and leave the rest to the default. Alternatively, you can define the whole method and choose the Color, line Thickness, and type of corners; rounded or not.

    public LineBorder(Color color) {
        this(color, 1, false);
    }
    public LineBorder(Color color, int thickness)  {
        this(color, thickness, false);
    }
    @ConstructorProperties({"lineColor", "thickness", "roundedCorners"})
    public LineBorder(Color color, int thickness, boolean roundedCorners)  {
        lineColor = color;
        this.thickness = thickness;
        this.roundedCorners = roundedCorners;
    }
Balanchine answered 11/4, 2019 at 15:56 Comment(0)
S
0

Create a line border with the specified color and width

Border border = BorderFactory.createLineBorder(Color.BLUE, 5);

Set the border of this component

 JTextField.setBorder(border);
Sannyasi answered 1/6, 2019 at 6:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.