import java.awt.*;
import javax.swing.border.*;
public class Borders extends JApplet {
static JPanel showBorder(Border b) {
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
//獲得傳來參數所表示的類的名稱
String nm = b.getClass().toString();
nm = nm.substring(nm.lastIndexOf('.') + 1);
//產生Label並放在JPanel中間
jp.add(new JLabel(nm, JLabel.CENTER), BorderLayout.CENTER);
jp.setBorder(b);
return jp;
}
public void init() {
Container cp = getContentPane();
cp.setLayout(new GridLayout(2, 4));
cp.add(showBorder(new TitledBorder("Title")));//標題邊框
cp.add(showBorder(new EtchedBorder()));//浮雕化邊框
cp.add(showBorder(new LineBorder(Color.blue)));//實現單色、任意厚度線邊框
cp.add(showBorder(new MatteBorder(5, 5, 30, 30, Color.black)));//類似襯邊的邊框,後面的顏色是背景色
cp.add(showBorder(new BevelBorder(BevelBorder.LOWERED)));//雙線斜面邊框
cp.add(showBorder(new SoftBevelBorder(BevelBorder.LOWERED)));//比上一種拐角圓滑
cp.add(showBorder(new CompoundBorder(new EtchedBorder(),
new LineBorder(Color.red))));//組合邊框
}
public static void main(String[] args) {
Borders applet = new Borders();
JFrame frame = new JFrame(applet.getClass().toString().substring(6));//建立一個名字爲Buttons的frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//frame關閉方法
frame.getContentPane().add(applet);
applet.init();
applet.start();
frame.setSize(300, 300);
frame.setVisible(true);
}
}
本文的精華部分在init()函數當中,創建了各種各樣的邊框,我已經在程序中作了註釋,這裏我不再解釋。
值得學習的一點。建立一個函數來專門生成Border,是我們在編程中應當學習的東西