Java Swing Jtextfield 的圆角边框

9
当我执行以下操作时:
LineBorder lineBorder =new LineBorder(Color.white, 8, true);
jTextField2.setBorder(lineBorder );

我得到的结果如下图:

enter image description here

如何在不显示方角和剪切一半文本的情况下获得圆角边框?
非常感谢。
最好的祝愿。

2
-1,您几周前曾经问过这个问题:https://dev59.com/Ol3Va4cB1Zd3GeqPDLu3#8305672 - camickr
@camickr 谢谢,没有意识到重复 - 我会投票关闭这个问题。 - kleopatra
4个回答

19

你可以覆盖JTextFiled来构建自己的圆角JTextField。你需要重写它的paintComponent(), paintBorder(),和contains()方法。你需要画一个圆角矩形作为文本框的形状。

例如:

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

2

1

非常类似于@Harry Joy的答案-只是走了更远的路程,如最近的一个答案中所概述的

  • 定义一个公开形状的边框类型
  • 使组件意识到可能有形状的边框
  • 如果检测到有形状的边框,请在形状内的paintComponent中接管背景绘制(无需触及paintBorder)

1

这将修改整个应用程序中创建的任何JTextField。

在您的第一个窗口的开始处加入它,它将影响每个JTextField。

    UIManager.put("TextField.background", Color.WHITE);
    UIManager.put("TextField.border", BorderFactory.createCompoundBorder(
            new CustomeBorder(), 
            new EmptyBorder(new Insets(4,4,4,4))));

自定义边框。
@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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接