When I do :
LineBorder lineBorder =new LineBorder(Color.white, 8, true);
jTextField2.setBorder(lineBorder );
I get this result like:
How can I have rounded borders without the squared corners visible and the text half cut ?
Thank you very much.
Best regards
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);
There is a simple example here:
http://java-swing-tips.blogspot.com.ar/2012/03/rounded-border-for-jtextfield.html
Regards!
Very similar to @Harry Joy's answer - just going the full distance, as outlined in a recent answer
- define a border type which exposes a shape
- make the component aware of a possibly shaped border
- if it detects the shaped border, take over the background painting in paintComponent inside the shape (no need to touch paintBorder)
This will modify any JTextField that you create in the entire application
Drop it just at the beginning of your very first window, it will affect every JTextField.
UIManager.put("TextField.background", Color.WHITE);
UIManager.put("TextField.border", BorderFactory.createCompoundBorder(
new CustomeBorder(),
new EmptyBorder(new Insets(4,4,4,4))));
The custom border
@SuppressWarnings("serial")
public static class CustomeBorder extends AbstractBorder{
@Override
public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height) {
super.paintBorder(c, g, x, y, width, height);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(COLOR_BORDE_SIMPLE);
Shape shape = new RoundRectangle2D.Float(0, 0, c.getWidth()-1, c.getHeight()-1,9, 9);
g2d.draw(shape);
}
}