如何在* ComponentUI类(Swing应用程序)中设置默认的首选大小(重新定义UI)? [英] How to set a default preferred size (redefining UI) in a *ComponentUI class (Swing app)?
问题描述
我扩展了系统外观,以绘制自定义JButton
.
I extended the system look and feel to draw custom 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()
.我该怎么办?
Now I would like to add that constraint on these buttons: I want the buttons to have size of 70x24 except if a setPreferredSize()
has been called in the client code. How can I do that?
注意:如果将setPreferredSize()
放在MyButtonUI.update()
方法中,它将覆盖客户端setPreferredSize()
,那么我所有的按钮都将具有相同的大小.
Note: If I put a setPreferredSize()
in the MyButtonUI.update()
method, it overrides the client setPreferredSize()
, then all my buttons get the same size.
谢谢.
多亏了纪尧姆,我这样重写了getPreferredSize()
(在MyButtonUI
中):
Thanks to Guillaume, I overrided getPreferredSize()
(in MyButtonUI
) like this:
@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);
}
它工作正常.
推荐答案
仅重写类MyButtonUI
中的方法getPreferredSize()
.如果程序员自愿将首选大小设置为其他大小,则不会调用您的代码.这是JComponent的默认行为.
Simply override the method getPreferredSize()
in your class MyButtonUI
. If a programmer voluntarily sets the preferred size to something else, your code will not be called. That is the default behaviour of JComponent.
请参见getPreferredSize()
的代码:
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
Dimension size = null;
if (ui != null) {
size = ui.getPreferredSize(this);
}
return (size != null) ? size : super.getPreferredSize();
}
这篇关于如何在* ComponentUI类(Swing应用程序)中设置默认的首选大小(重新定义UI)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!