我想创建自己的外观并派生出MetalLookAndFeel。我已经设置了一个非常基本的配置,其中所有文件都在同一目录中,并且没有包声明:
MyLookAndFeel.java
import javax.swing.UIDefaults;
import javax.swing.plaf.basic.BasicLookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;
public class MyLookAndFeel extends MetalLookAndFeel {
public MyLookAndFeel() {
setCurrentTheme(new DefaultMetalTheme());
}
@Override
protected void initClassDefaults(UIDefaults table) {
super.initClassDefaults(table);
table.put( "ButtonUI", "MyButtonUI");
}
@Override
public String getName() {
return "MyLookAndFeel";
}
@Override
public String getID() {
return "MyLookAndFeel";
}
@Override
public String getDescription() {
return "MyLookAndFeel";
}
@Override
public boolean isNativeLookAndFeel() {
return false;
}
@Override
public boolean isSupportedLookAndFeel() {
return true;
}
}
我们还有MyButtonUI.java:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.AbstractButton;
import javax.swing.JComponent;
import javax.swing.plaf.metal.MetalButtonUI;
public class MyButtonUI extends MetalButtonUI {
@Override
public void paint(Graphics g, JComponent c) {
}
@Override
protected void paintButtonPressed(Graphics g, AbstractButton b) {
g.fillRect(0, 0, 40, 40);
}
@Override
protected void paintText(Graphics g, AbstractButton b, Rectangle textRect,
String text) {
}
}
使用上面的代码,我希望当我使用这个构造函数运行paint
类时,将会绘制一个奇怪的按钮(或者根本没有按钮,因为TestUI JFrame
方法为空),但是按钮看起来很安静正常:
public TestUI() throws UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(new MyLookAndFeel());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,200);
setLayout(new FlowLayout());
add(new JButton("Press"));
add(new JLabel("Text"));
setVisible(true);
}
我忘了重要的事吗?
答案 0 :(得分:2)
"MyButtonUI"
应该是完整路径(与jar中打包的Icon相同)或有效的类名称,例如UIManager.put("ButtonUI", MyButtonUI.class.getName());
覆盖BasicButtonUI
,与其他LaF的接口可以为空,不覆盖所有System LaFs
的所有方法,而不是MetalButtonUI
,您的自定义MetalButtonUI
在UIManager
也许是will help you partial workaround for MetalButtonUI,也许没有理由向UIManager
注册自定义用户界面,确定最后的决定是你的
答案 1 :(得分:1)
在你的类MyButtonUI中,你必须实现一个公共静态方法createUI()。像这样:
public static ComponentUI createUI(JComponent c)
{
return new MyButtonUI ();
}
或者为所有按钮返回一个共享实例。