Java Swing为Jtextfield舍入边框 [英] Java Swing rounded border for Jtextfield

查看:585
本文介绍了Java Swing为Jtextfield舍入边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我这样做时:

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

我得到的结果如下:

我怎样才能圆润边框没有方形角可见,文字切成一半?

How can I have rounded borders without the squared corners visible and the text half cut ?

非常感谢。

祝你好运

推荐答案

你可以覆盖 JTextFiled 建立你自己的圆角的JTextField 。你必须覆盖它的 paintComponent() paintBorder(),并且包含()方法。您需要将roundRect绘制为文本字段的形状。

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.

示例:

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

这篇关于Java Swing为Jtextfield舍入边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆