《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class Test extends JApplet {
public void init() {
JPanel jpanel = new AllBordersPanel();
getContentPane().add(jpanel, BorderLayout.CENTER);
}
}
class AllBordersPanel extends JPanel {
public AllBordersPanel() {
JPanel bl = new PanelWithTitle("Bevel Lowered"),
br = new PanelWithTitle("Bevel Raised"),
c = new PanelWithTitle("Compound"),
l = new PanelWithTitle("Line"),
m = new PanelWithTitle("Matte"),
e = new PanelWithEmptyBorder("Empty"),
t = new PanelWithTitle("Titled"),
sbr = new PanelWithTitle("Soft Bevel Raised"),
sbl = new PanelWithTitle("Soft Bevel Lowered"),
el = new PanelWithTitle("Etched Lowered"),
er = new PanelWithTitle("Etched Raised");
setLayout(new GridLayout(4,3,2,2));
ImageIcon icon = new ImageIcon("smiley.gif");
Dimension iconsz = new Dimension(icon.getIconWidth(),
icon.getIconHeight());
bl.setBorder(BorderFactory.createLoweredBevelBorder());
br.setBorder(BorderFactory.createRaisedBevelBorder());
sbr.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
sbl.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
t.setBorder(BorderFactory.createTitledBorder("Titled"));
l.setBorder(
BorderFactory.createLineBorder(Color.black,2));
c.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.gray,10),
BorderFactory.createRaisedBevelBorder()),
BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(Color.blue,5),
BorderFactory.createLoweredBevelBorder())));
el.setBorder(BorderFactory.createEtchedBorder(
getBackground().brighter(),
getBackground().darker()));
er.setBorder(BorderFactory.createEtchedBorder(
getBackground().darker(),
getBackground().brighter()));
m.setBorder(BorderFactory.createMatteBorder(
iconsz.height, iconsz.width,
iconsz.height, iconsz.width,
icon));
add(br); add(bl); add(sbr);
add(sbl); add(c); add(el);
add(er); add(e); add(l);
add(m); add(t);
}
}
class PanelWithTitle extends JPanel {
private String title;
public PanelWithTitle(String title) {
this.title = title;
}
public void paintComponent(Graphics g) {
FontMetrics fm = g.getFontMetrics();
Dimension size = getSize();
int titleW = fm.stringWidth(title);
g.setColor(Color.black);
g.drawString(title, size.width/2 - titleW/2,
size.height/2);
}
}
class PanelWithEmptyBorder extends PanelWithTitle {
public PanelWithEmptyBorder(String title) {
super(title);
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
}
public void paintComponent(Graphics g) {
Dimension size = getSize();
Insets insets = getInsets();
g.setColor(Color.red);
g.fillRect(insets.left,insets.top,
size.width-2*insets.left,
size.height-2*insets.top);
super.paintComponent(g);
}
}