我只想为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
答案 0 :(得分:1)
您可以提供自定义ButtonUI,并将其用于按钮,而不是覆盖paintComponent()
。 Swing使用TextLayout
来绘制字符串,这可能会变得复杂。但是,BasicButtonUI有一个受保护的paintText()
方法可以执行您想要的操作(您不一定需要手动调用它。用户界面的paint()
会调用它,除非您也覆盖它) 。因此,如果你扩展BasicButtonUI
,你可以简单地让它绘制字符串。