今天給大家做了個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>
<p_w_picpathPainter method="buttonBackground" path="p_w_picpaths/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">
<p_w_picpathPainter method="buttonBackground" path="p_w_picpaths/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">
<p_w_picpathPainter method="buttonBackground" path="p_w_picpaths/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做控件皮膚的強大了?其他控件是相同的做法!