之前做一个程序希望能更换程序外观,在网上搜了一下,发现Java有一个Synth。是在Java 5.0引入得。这里有一个入门介绍讲得很好, http://www.ibm.com/developerworks/cn/java/j-synth/ 。但是这个演示版本还是太简单了,控件太少,比如连菜单都没有。后来实际使用时还是遇到了很多问题。这里把使用过程中遇到的问题和做法列出来,作个笔记。
第一步:
建立一个空的JAVA工程,我这里的IDE是netbeans8.0,JDK用的JDK 1.7
工程目录截图
MainFrame.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demo;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.synth.SynthLookAndFeel;
/**
*
* @author hufeiyan
*/
public class MainFrame extends JFrame {
private JPanel contentPanel;
public MainFrame() {
initialize();
}
public static void main(String args[]) {
try {
SynthLookAndFeel synth = new SynthLookAndFeel();
synth.load(MainFrame.class.getResourceAsStream("synthskin.xml"), MainFrame.class);
UIManager.setLookAndFeel(synth);
} catch (ParseException | UnsupportedLookAndFeelException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MainFrame mf = new MainFrame();
mf.setLocationRelativeTo(null);
mf.setVisible(true);
}
});
}
private void initialize() {
this.setSize(400, 600);
this.setContentPane(getJContentPane());
this.setTitle("Synth Look Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private javax.swing.JPanel getJContentPane() {
if (contentPanel == null) {
contentPanel = new JPanel();
}
return contentPanel;
}
}
其中下面三行实现Synth外观的加载使用。
<span style="white-space:pre"> </span> SynthLookAndFeel synth = new SynthLookAndFeel();
synth.load(MainFrame.class.getResourceAsStream("synthskin.xml"), MainFrame.class);
UIManager.setLookAndFeel(synth);
SynthSkin.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<synth>
</synth>
当前SynthSkin.xml是一个空文件,没有定义任何外观内容。注意:根元素必须是synth,否则会产生解析异常。
程序运行效果:
目前看起来是一个没有任何效果。
SynthLookAndFeel 是一个空白外观,本身比提供任何默认外观及行为,所有的绘制效果都是通过委托处理的。我们现在得文件中只有一个根元素,没有定义任何外观,所以运行结果没有体现外观改变。
这里疑问:
图中窗口(实际的JPanel控件)现在的背景颜色为什么是灰色的,这个颜色是如何确定的?