我正在创建一个自定义按钮,我无法让它在大多数内置PLAF上看起来正确。
这是我的代码
public MyButton(String text, Icon icon) {
if (icon == null) icon = createDefaultIcon();
mainButton = new JButton(text);
popupButton = new JButton(icon);
removeBorder(mainButton);
removeBorder(popupButton);
setModel(new DefaultButtonModel());
setBorder(UIManager.getBorder("Button.border"));
int popupButtonWidth = popupButton.getPreferredSize().width;
int popupButtonHeight = mainButton.getPreferredSize().height;
Dimension popupButtonSize = new Dimension(popupButtonWidth, popupButtonHeight);
popupButton.setMinimumSize(popupButtonSize);
popupButton.setPreferredSize(popupButtonSize);
popupButton.setMaximumSize(popupButtonSize);
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(mainButton);
add(new JSeparator(VERTICAL));
add(popupButton);
}
private void removeBorder(JButton button) {
Border border = button.getBorder();
if (border instanceof CompoundBorder) {
button.setBorder(((CompoundBorder) border).getInsideBorder());
} else {
button.setBorder(BorderFactory.createEmptyBorder());
}
}
以下是按钮在计算机上安装的PLAF中的显示方式
金属
雨云
CDE /基序
Mac OS X
CDE / Motif是唯一正常运行的。我查看了一些ButtonUI的源代码,看起来他们可以忽略背景颜色和边框。不幸的是背景颜色和边框是我需要设置的。如何让我的自定义按钮正确支持内置PLAF?
修改 根据要求,这是我用来生成图像的代码
public class MyButtonDemo implements Runnable {
public void run() {
// Change the array index to get a different PLAF
try {
UIManager.setLookAndFeel(UIManager.getInstalledLookAndFeels()[0].getClassName());
} catch (Exception ignored) { }
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(new MyButton("My Button", null);
frame.getContentPane().add(new JButton("Normal Button"));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MyButtonDemo());
}
}
答案 0 :(得分:0)
欢迎来到可插拔外观的精彩世界;感觉。我能想到的唯一真正的选择就是提供。每个平台的UI代表或查看Syththetic UI
答案 1 :(得分:0)
不确定我做了什么,但现在除了Nimbus之外它现在都在工作。这是代码
public MyButton(String text, Icon icon) {
arrowIcon = createDefaultArrowIcon();
mainButton = new JButton(text, icon);
popupButton = new JButton(arrowIcon);
mainButton.setBorder(BorderFactory.createEmptyBorder());
popupButton.setBorder(BorderFactory.createEmptyBorder());
setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
add(mainButton);
add(new JSeparator(VERTICAL));
add(popupButton);
setModel(new DefaultButtonModel());
init(null, null);
}
@Override
public void updateUI() {
setUI((ButtonUI)UIManager.getUI(this));
}
@Override
public String getUIClassID() {
return "ButtonUI";
}