我通过扩展 Jbutton 为我的应用程序创建了一个自定义按钮,并且我已经让它按照我想要的方式绘制,但由于某种原因,即使我setMargin()
在构造函数中调用,按钮的边距为 0,如下所示:
我的代码有什么地方做错了吗?标准 JButtons 有边距,但我的自定义按钮没有边距是怎么回事?
我的按钮的java代码:
public class CToolbarButton extends JButton
{
private static final Dimension SIZE = new Dimension(48, 48);
private static final int MARGIN_VAL = 50;
private static final Insets MARGIN = new Insets(MARGIN_VAL, MARGIN_VAL, MARGIN_VAL, MARGIN_VAL);
private static final Color FILL_NORM = Color.GRAY;
private static final Color FILL_ACTIVE = new Color(FILL_NORM.getRed()-25, FILL_NORM.getGreen()-25, FILL_NORM.getBlue()-25);
private static final Color BORDER_NORM = Color.BLACK;
private static final Color BORDER_ACTIVE = Color.YELLOW;
public CToolbarButton()
{
super();
setContentAreaFilled(false);
setFocusable(false);
setMargin(MARGIN);
}
@Override
public void paintComponent(Graphics g)
{
if (getModel().isArmed())
{
g.setColor(FILL_ACTIVE);
}
else
{
g.setColor(FILL_NORM);
}
g.fillRect(0, 0, getWidth(), getHeight());
}
@Override
public void paintBorder(Graphics g)
{
if (getModel().isArmed())
{
g.setColor(BORDER_ACTIVE);
}
else
{
g.setColor(BORDER_NORM);
}
g.drawRect(0, 0, getWidth(), getHeight());
}
@Override
public boolean contains(int x, int y)
{
return (x >= 0 &&
x <= getWidth() &&
y >= 0 &&
y <= getHeight());
}
@Override
public Dimension getPreferredSize()
{
return SIZE;
}
@Override
public Dimension getMinimumSize()
{
return SIZE;
}
@Override
public Dimension getMaximumSize()
{
return SIZE;
}
}