作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个自定义按钮,但我无法让它在大多数内置 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());
}
}
最佳答案
欢迎来到可插拔外观的美妙世界。我能想到的唯一真正的选择就是提供。每个平台的 UI 委托(delegate)或查看 Syththetic UI
关于java - 如何将内置的 PLAF 与自定义组件一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11699931/
我是一名优秀的程序员,十分优秀!