java swing边框,Java Swing为Jtextfield舍入边框

When I do :

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

jTextField2.setBorder(lineBorder );

I get this result like:

7wWkU.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值