Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing rounded border for Jtextfield

When I do :

LineBorder lineBorder =new LineBorder(Color.white, 8, true);
jTextField2.setBorder(lineBorder );

I get this result like:

enter image description here

How can I have rounded borders without the squared corners visible and the text half cut ?

Thank you very much.

Best regards

like image 998
Vincent Roye Avatar asked Dec 15 '11 05:12

Vincent Roye


2 Answers

You can override JTextFiled build your own Rounded corner JTextField. You have to override it's paintComponent(), paintBorder(), and contains() methods. You need to draw roundRect as the shape of text field.

Example:

public class RoundJTextField extends JTextField {
    private Shape shape;
    public RoundJTextField(int size) {
        super(size);
        setOpaque(false); // As suggested by @AVD in comment.
    }
    protected void paintComponent(Graphics g) {
         g.setColor(getBackground());
         g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
         super.paintComponent(g);
    }
    protected void paintBorder(Graphics g) {
         g.setColor(getForeground());
         g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
    }
    public boolean contains(int x, int y) {
         if (shape == null || !shape.getBounds().equals(getBounds())) {
             shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
         }
         return shape.contains(x, y);
    }
}

To see this in effect:

    JFrame frame = new JFrame("Rounded corner text filed demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setLayout(new FlowLayout());
    JTextField field = new RoundJTextField(15);
    frame.add(field);
    frame.setVisible(true);
like image 185
Harry Joy Avatar answered Sep 27 '22 16:09

Harry Joy


There is a simple example here: http://java-swing-tips.blogspot.com.ar/2012/03/rounded-border-for-jtextfield.html

Regards!

like image 24
Emiliano Schiano Avatar answered Sep 27 '22 16:09

Emiliano Schiano