gpt4 book ai didi

Jtextfield 的 Java Swing 圆形边框

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:20 24 4
gpt4 key购买 nike

当我这样做时:

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

我得到这样的结果:

enter image description here

如何在不显示方角和文本半切的情况下设置圆角边框?

非常感谢。

最好的问候

最佳答案

您可以覆盖 JTextFiled 构建您自己的圆角 JTextField。您必须覆盖它的 paintComponent()paintBorder()contains() 方法。您需要绘制 roundRect 作为文本字段的形状。

例子:

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

要查看效果:

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

关于Jtextfield 的 Java Swing 圆形边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8515601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com