JComponent同样包罗一个称为setBorder()的要领,该要领答允我们安顿一些各类百般有趣的边框到一些可见的组件上。下面的措施例子操作一个建设JPanel并安顿边框到每个例子中的被称为showBorder()的要领,示范了一些有用的差异的边框。同样,它也利用RTTI来找我们利用的边框名(剔除所有的路径信息),然后将边框名放到面板中间的JLable里:
//: Borders.java // Different Swing borders package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class Borders extends JPanel { static JPanel showBorder(Border b) { JPanel jp = new JPanel(); jp.setLayout(new BorderLayout()); String nm = b.getClass().toString(); nm = nm.substring(nm.lastIndexOf('.') + 1); jp.add(new JLabel(nm, JLabel.CENTER), BorderLayout.CENTER); jp.setBorder(b); return jp; } public Borders() { setLayout(new GridLayout(2,4)); add(showBorder(new TitledBorder("Title"))); add(showBorder(new EtchedBorder())); add(showBorder(new LineBorder(Color.blue))); add(showBorder( new MatteBorder(5,5,30,30,Color.green))); add(showBorder( new BevelBorder(BevelBorder.RAISED))); add(showBorder( new SoftBevelBorder(BevelBorder.LOWERED))); add(showBorder(new CompoundBorder( new EtchedBorder(), new LineBorder(Color.red)))); } public static void main(String args[]) { Show.inFrame(new Borders(), 500, 300); } } ///:~
这一节中大大都措施例子都利用TitledBorder,但我们可以留意到其余的边框也同样易于利用。能建设我们本身的边框并安顿它们到按钮、标签等等内——任何来自JComponent的对象。