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.
Only one line of user response will be accepted. If multiple lines are desired, JTextArea will be needed.
As the user inputs text value, it sets the value of the JTextField variable component. We can use a getter method to access this value input by the user, display it on JLabel, store it in a database, or display it in a JTable.
To put a border around a JComponent , you use its setBorder method. You can use the BorderFactory class to create most of the borders that Swing provides. If you need a reference to a border — say, because you want to use it in multiple components — you can save it in a variable of type Border .
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.
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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With