我在练习写一个小游戏组件Tetris, 以及这个组件的两个不同的UI: TetrisUI_1,TetrisUI_2
重载JComponent.updateUI()时 public void updateUI() {
// setUI(new TetrisUI_1()); // 不希望直接写成这样
setUI((ButtonUI)UIManager.getUI(this)); // 希望写成这样
}请问如何将UI通过UIManager与这个组件关联?
两个UI如何通过UIManager切换?
重载JComponent.updateUI()时 public void updateUI() {
// setUI(new TetrisUI_1()); // 不希望直接写成这样
setUI((ButtonUI)UIManager.getUI(this)); // 希望写成这样
}请问如何将UI通过UIManager与这个组件关联?
两个UI如何通过UIManager切换?
如果希望是单例 通过static保证实例长驻且不被外部直接初始化
UIManager.setLookAndFeel(lookAndFeel);
或者在别的地方设置
总之要在updateUI前设置
这样刷新的时候就把ui换掉了
UIManager.setLookAndFeel()是设置整个程序的LAF, 现在只是增加一个组件的UI
这样行不通吧
private static final String uiClassID = "TetrisUI";
public String getUIClassID() {
return uiClassID;
}
// ...
}
public class Test extends JFrame {
public static void main(String[] args) {
UIManager.getDefaults().put("TetrisUI", "com.*.TetrisUI_1"); // UI与组件关联
// ...
}
}
public void actionPerformed(java.awt.event.ActionEvent e) {
if(UIManager.getDefaults().containsKey("TetrisUI")) {
UIManager.getDefaults().remove("TetrisUI");
}
UIManager.getDefaults().put("TetrisUI", "com.*.TetrisUI_2");
}不会生效呢
继续请教...
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;import com.sun.java.swing.plaf.windows.WindowsButtonUI;public class TestLookAndFeel extends JFrame { private TestButton lookAndFeelButton; public TestLookAndFeel() {
this.initParam();
JPanel contentPanel = new JPanel();
contentPanel.add(this.lookAndFeelButton);
this.getContentPane().add(contentPanel);
} private void initParam() {
this.lookAndFeelButton = new TestButton("lookAndFeelButton");
this.lookAndFeelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
UIManager.getDefaults().put("ButtonUI", "ButtonUI2");
TestLookAndFeel.this.lookAndFeelButton.setChangeUI(true);
TestLookAndFeel.this.lookAndFeelButton.updateUI();
}
});
} /**
* @param args
*/
public static void main(String[] args) {
TestLookAndFeel test = new TestLookAndFeel();
test.setVisible(true);
test.setSize(200, 200);
test.setDefaultCloseOperation(EXIT_ON_CLOSE);
} class TestButton extends JButton {
private boolean changeUI = false; public TestButton(String string) {
super(string);
} public String getUIClassID() {
if (this.changeUI) {
this.changeUI = false;
return UIManager.getDefaults().getString("ButtonUI");
}
return super.getUIClassID();
} @Override
public void updateUI() {
if ("ButtonUI2".equals(getUIClassID())) {
this.setUI(new WindowsButtonUI());
} else {
super.updateUI();
}
} public void setChangeUI(boolean changeUI) {
this.changeUI = changeUI;
}
}
}
public void actionPerformed(java.awt.event.ActionEvent e) {
if(UIManager.getDefaults().containsKey("TetrisUI")) {
UIManager.getDefaults().remove("TetrisUI");
}
UIManager.getDefaults().put("TetrisUI", "com.*.TetrisUI_2");
// tetris.updateUI(); // 更新单个组件
SwingUtilities.updateComponentTreeUI(gamePanel); // 更新整个组件树
}