今天给大家做了个button的synth实例。
首先要创建一个java文件,定义一个button的类,并且在类里面初始化button。画出来
代码如下:
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.plaf.synth.SynthLookAndFeel;
public class MyButton {
JFrame frame = new JFrame("Test synth");
JButton btn = new JButton("Sure");
public MyButton(){
frame.setLayout(new FlowLayout());
frame.setPreferredSize(new Dimension(300, 300));
frame.setBounds(400, 400, 0, 0);
btn.setPreferredSize(new Dimension(100,100));
frame.getContentPane().add(btn);
}
public void show(){
frame.pack();
frame.show();
}
}
其次呢,就是把button和它的样式文件xml文件绑定起来,这个要在main函数中做处理;代码如下:
public static void main(String[] args){
SynthLookAndFeel slf = new SynthLookAndFeel();
try {
slf.load(MyButton.class.getResourceAsStream("mybutton.xml"), MyButton.class);
UIManager.setLookAndFeel(slf);
} catch (Exception e) {
e.printStackTrace();
return;
}
MyButton mBtn = new MyButton();
mBtn.show();
}
再次呢,就是创作样式xml文件,代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<synth>
<style id="mybutton">
<state>
<imagePainter method="buttonBackground" path="images/001.png"
sourceInsets="9 10 9 12" paintCenter="true" stretch="true"/>
<insets top="9" left="10" bottom="9" right="12"/>
<font name="Aharoni" size="16"/>
<color type="TEXT_FOREGROUND" value="#FFFFFF"/>
</state>
<state value="MOUSE_OVER">
<imagePainter method="buttonBackground" path="images/002.png"
sourceInsets="9 10 9 12" paintCenter="true" stretch="true"/>
<insets top="9" left="10" bottom="9" right="12"/>
<color type="TEXT_FOREGROUND" value="#FFFFFF"/>
</state>
<state value="PRESSED">
<imagePainter method="buttonBackground" path="images/003.png"
sourceInsets="10 12 8 9" paintCenter="true" stretch="true"/>
<insets top="10" left="12" bottom="8" right="9"/>
<color type="TEXT_FOREGROUND" value="#FFFFFF"/>
</state>
<property key="Button.margin" type="insets" value="0 0 0 0"/>
</style>
<bind style="mybutton" type="region" key="Button"/>
</synth>
这样,运行下看下效果,是不是就已经知道了synth做控件皮肤的强大了?其他控件是相同的做法!