Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get one side(i.e., right bordered line) of the jtextfield colored

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.

like image 971
Kanth Avatar asked Aug 13 '12 13:08

Kanth


People also ask

Can you enter more than one line in a JTextField?

Only one line of user response will be accepted. If multiple lines are desired, JTextArea will be needed.

What method should you use to get the value of a JTextField?

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.

How do you put a border on a swing?

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 .


3 Answers

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.

like image 118
Jacob Raihle Avatar answered Oct 04 '22 05:10

Jacob Raihle


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

like image 20
Timmo Avatar answered Oct 04 '22 05:10

Timmo


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:

  • http://docs.oracle.com/javase/7/docs/api/javax/swing/border/Border.html
like image 22
David Kroukamp Avatar answered Oct 04 '22 05:10

David Kroukamp