Java Swing rounded border for Jtextfield

Vincent Roye picture Vincent Roye · Dec 15, 2011 · Viewed 22.8k times · Source

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

Answer

Harry Joy picture Harry Joy · Dec 15, 2011

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);