Java Swing为Jtextfield舍入边框

Vin*_*oye 5 java swing rounded-corners jtextfield

当我做 :

LineBorder lineBorder =new LineBorder(Color.white, 8, true);
jTextField2.setBorder(lineBorder );
Run Code Online (Sandbox Code Playgroud)

我得到这样的结果:

在此输入图像描述

如何在没有方形角可见且文本切半的情况下使用圆形边框?

非常感谢你.

最好的祝福

Har*_*Joy 14

您可以覆盖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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要看到这个有效:

    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);
Run Code Online (Sandbox Code Playgroud)