2013-10-07 30 views
0

我只是想为JButton设置不同的风格。所以我重写了paintComponent来实现。它工作成功,但此按钮不支持HTML格式。覆盖JButton paintComponent不同的风格不支持HTML格式

请你建议我

paintComponent() 
~~~~~~~~~~~~~~~~ 
this is below my override code: 
// prep for painting. 
     Graphics2D g2D = (Graphics2D)g; 
     if(buttonStyle != 0 && buttonStyle != IMAGES){ 
     if(g == null) 
      return; 
     if(getBackground() == null) 
      setBackground(acrcolor); 
     if(getFadedBackgroundColor() == null) 
      setFadedBackgroundColor(Color.white); 

     g2D.clearRect(0, 0, getWidth()+getX(), getHeight()+getY()); 
     // end prep for painting. 
     } 
     switch (buttonStyle){ 
     case SKINZ: 
     paintSkinz(g2D); 
     return; 
     case IMAGES: 
     paintImages(g2D); 
     break; 
     case ROLLOVER: 
     System.err.println("Rollover look of FuelButton not yet implemented."); 
     break; 
     case JAVA_LIKE: 
     paintJavaLike(g2D); 
     return; 
     case GRADIENCE: 
     paintGradience(g2D); 
     case CLASSIC: 
     case JAVA_DEFAULT: 
     default:   
     super.paintComponent(g); 
     m_originalborder = getBorder(); 
     m_originalfont = getFont(); 
     return; 
     } 
     paintText(g2D,0,0,getWidth(),getHeight()); 


paintJavaLike(g2D): 
~~~~~~~~~~~~~~~~~~~~ 
g2D.setColor(getBackground()); 
     g2D.fill3DRect(0,0,getWidth(),getHeight(),true); 
     if(getIcon()==null) 
     paintText(g2D,0,0,getWidth(),getHeight()); 
     else if (getText() == null || getText().length() == 0) 
     this.paintCenteredIcon(g2D, ((ImageIcon)getIcon()).getImage()); 
     else { 
     int w = getWidth() - getIconTextGap() - getIcon().getIconWidth() - (borderWidth*2)-4; 
     int h = getHeight()-(borderWidth*2); 
     g2D.drawImage(((ImageIcon)getIcon()).getImage(), 2, (getHeight()/2)-(getIcon().getIconHeight()/2), this); 
     paintText(g2D,2+getIcon().getIconWidth()+this.getIconTextGap(),0,w,h); 
     } 

感谢 Palanisamy

回答

1

你可以提供自定义ButtonUI和使用的按钮,而不是覆盖paintComponent()。 Swing使用TextLayout来绘制字符串,这可能会变得复杂。然而,BasicButtonUI具有保护paintText()方法,可以做你想做的(你不一定需要手动调用它。该UI的paint()调用它,除非你重写过)。所以如果你延伸BasicButtonUI你可以简单地让它画出字符串。

+1

[例如(http://stackoverflow.com/questions/5751311/creating-a-custom-button-in-java-with-jbutton/5755124#5755124) – mKorbel