【问题标题】:Java Swing rounded border for JtextfieldJtextfield 的 Java Swing 圆形边框
【发布时间】:2017-07-14 01:51:34
【问题描述】:

当我这样做时:

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

我得到这样的结果:

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

非常感谢。

最好的问候

【问题讨论】:

标签: java swing jtextfield rounded-corners


【解决方案1】:

您可以覆盖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);

【讨论】:

    【解决方案2】:

    【讨论】:

      【解决方案3】:

      与@Harry Joy 的回答非常相似 - 就像outlined in a recent answer 一样,只是走了完整的路

      • 定义显示形状的边框类型
      • 让组件知道可能的形状边框
      • 如果检测到异形边框,则接管该形内paintComponent中的背景绘制(无需触摸paintBorder)

      【讨论】:

        【解决方案4】:

        这将修改您在整个应用程序中创建的任何 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);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-09
          • 2011-01-17
          • 2011-10-25
          • 2021-12-05
          • 1970-01-01
          • 2012-01-08
          • 1970-01-01
          相关资源
          最近更新 更多