gpt4 book ai didi

java - 如何将内置的 PLAF 与自定义组件一起使用?

转载 作者:行者123 更新时间:2023-11-29 09:12:12 26 4
gpt4 key购买 nike

我正在创建一个自定义按钮,但我无法让它在大多数内置 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 中的样子

金属

My Custom Button Metal PLAF Example

光轮

My Custom Button Nimbus PLAF Example

CDE/主题

My Custom Button CDE/Motif PLAF Example

Mac OS X

My Custom Button Mac OS PLAF Example

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com