【问题标题】:how i remove unneeded background under roundedborder?我如何删除圆形边框下不需要的背景?
【发布时间】:2012-04-04 20:49:14
【问题描述】:

我使用类来制作圆角边框

班级是:

public class RoundedBorder implements Border {
        int radius;

        public RoundedBorder(int radius) {
            this.radius = radius;
        }
    @Override
        public Insets getBorderInsets(Component c) {
            return new Insets(this.radius/2, this.radius, this.radius/2, this.radius);
        }
    @Override
        public boolean isBorderOpaque() {
            return true;
        }
    @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D graphics = (Graphics2D) g;
            graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            g.drawRoundRect(x,y,width-1,height-1,radius,radius);           
        }
    }

对于我使用的按钮:

JTextField login_nickname = new JTextField();

login_nickname.setBorder(new RoundedBorder(10));
login_nickname.setPreferredSize(new Dimension(150, 25));

它工作得很好,但我想删除角落圆角边框之外未使用的背景,我附上图片来解释我的意思,

谢谢

【问题讨论】:

  • 1) "i used class to make.." 请使用 shift 键在句首以及单词'I'处制作大写字母.这样做有助于读者。 2) 为了尽快获得更好的帮助,请发帖SSCCE

标签: java swing rounded-corners


【解决方案1】:

返回什么?

boolean isBorderOpaque();

不应该是“假”吗?

【讨论】:

    【解决方案2】:

    我会在paintBorder()中做这样的事情:

    @Override
     public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
         Graphics2D graphics = (Graphics2D) g;
         graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         if (c.getParent() != null) {
             Color bc = g.getColor();
             g.setColor(c.getParent().getBackground());
             for (int r = 0; r<radius;r++){
                g.drawRoundRect(x, y, width - 1, height - 1, r, r);
             }
             g.setColor(bc);
         }
         g.drawRoundRect(x, y, width - 1, height - 1, radius, radius);
     }
    

    如果组件有一些父容器,我会先用背景颜色绘制边框,然后在它的顶部 - 我的圆形边框。

    【讨论】:

    • 编辑了底层边框,使圆形边框在任何半径下都看起来很平滑
    • 非常感谢:),我还有一个小问题,如果我想将 BevelBorder.RAISED 添加到绘制的圆形边框,我将添加或修改什么方法?
    • 您应该查看 BevelBorder.RAISED 的paintBorder 方法,并使用类似的代码制作自己的边框,但带有圆角。如果我记得的话,斜面边框用 2 种不同的颜色和 2 条线绘制,所以你只需使用 g.drawRoundRect 做同样的事情。请记住,如果您用 2 条线绘制边框,则内线半径应小于外线半径 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多