我扩展了系统外观以绘制自定义JButton
。
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("ButtonUI", "com.my.package.MyButtonUI");
与com.my.package.MyButtonUI
:
public class MyButtonUI extends BasicButtonUI {
public static final int BTN_HEIGHT = 24;
private static final MyButtonUI INSTANCE = new MyButtonUI ();
public static ComponentUI createUI(JComponent b) {
return INSTANCE;
}
@Override
public void paint(Graphics g, JComponent c) {
AbstractButton b = (AbstractButton) c;
Graphics2D g2d = (Graphics2D) g;
GradientPaint gp;
if (b.isEnabled()) {
gp = new GradientPaint(0, 0, Color.red, 0, BTN_HEIGHT * 0.6f, Color.gray, true);
} else {
gp = new GradientPaint(0, 0, Color.black, 0, BTN_HEIGHT * 0.6f, Color.blue, true);
}
g2d.setPaint(gp);
g2d.fillRect(0, 0, b.getWidth(), BTN_HEIGHT);
super.paint(g, b);
}
@Override
public void update(Graphics g, JComponent c) {
AbstractButton b = (AbstractButton) c;
b.setForeground(Color.white);
paint(g, b);
}
}
现在我想在这些按钮上添加该约束:我希望按钮的大小为 70x24,除非setPreferredSize()
在客户端代码中调用了 a。我怎样才能做到这一点?
注意:如果我setPreferredSize()
在MyButtonUI.update()
方法中放了 a ,它会覆盖 client setPreferredSize()
,那么我所有的按钮都会得到相同的大小。
谢谢你。
编辑:
感谢 Guillaume,我像这样覆盖getPreferredSize()
了 (in MyButtonUI
):
@Override
public Dimension getPreferredSize(JComponent c) {
AbstractButton button = (AbstractButton) c;
int width = Math.max(button.getWidth(), BUTTON_WIDTH);
int height = Math.max(button.getHeight(), BUTTON_HEIGHT);
return new Dimension(width, height);
}
它工作正常。