2012-03-20 30 views
2

我用类做圆角的边框我是如何在圆角下移除不需要的背景的?

类是:

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

和它的工作很好,但我想删除未使用的背景外圆角边框在角落,我附图解释更多我的意思,

enter image description here

谢谢

+0

1)*“我用班级制作..”*请使用shift键在句子的开头以及单词'I'中写上大写字母。这样做可以帮助读者。 2)为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2012-03-20 11:34:17

+0

可能的重复 - http://stackoverflow.com/questions/8416295/component-painting-outside-custom-border – mre 2012-03-20 12:18:57

回答

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

如果组件有一些父容器,我会先绘制边框与背景颜色,然后在它上面 - 我轮边界。

+0

编辑底层边框,使圆角边框看起来光滑,任何半径 – yggdraa 2012-03-20 12:21:49

+0

非常感谢:),我有额外的小问题,如果我想添加BevelBorder.RAISED到绘制的圆形边框,我将添加或将要修改的方法是什么? – Jason4Ever 2012-03-22 09:26:37

+0

您应该查看BevelBorder.RAISED的paintBorder方法,并使您自己的边框使用类似的代码但圆角。如果我记得,斜面边框用2种不同的颜色和2行绘制,所以你只需要使用g.drawRoundRect。并且请记住,如果您用2条线将边界删除,则内部线半径应该小于外部的一条:) – yggdraa 2012-03-22 10:18:49

1

什么是返回的?

boolean isBorderOpaque(); 

不应该是'假'?