/*
涉及Panel中的图片的加载,还有Frame的关闭的方法, CardLayout(int hgap, int vgap)就会决定卡片面板的大小
匿名类的使用。。。
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo extends Frame{
Panel pCards=new Panel();//卡片面板
CardLayout Clayout=new CardLayout(120, 50);//设置卡片和面板边界的垂直和水平距离
public CardLayoutDemo(){
setLayout(new BorderLayout(100, 20));
Panel pBtn = new Panel();//按钮面板 pCards.setLayout(Clayout);
//pCards.setPreferredSize(new Dimension(30,40));//这句不再起作用了:因为其父类CardLayoutDemo使用的是BorderLayout布局方式,会自动填充
pCards.setBackground(Color.red);
pBtn.setBackground(Color.yellow);
pBtn.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
pBtn.setPreferredSize(new Dimension(200, 50)); Button tmpB;
pBtn.add(tmpB = new Button("第一张"));
tmpB.addActionListener(new myActionListener());
tmpB.setActionCommand("first");
pBtn.add(tmpB = new Button("下一张"));
tmpB.addActionListener(new myActionListener());
tmpB.setActionCommand("next"); pBtn.add(tmpB = new Button("前一张"));
tmpB.addActionListener(new myActionListener());
tmpB.setActionCommand("previous"); pBtn.add(tmpB = new Button("最后一张"));
tmpB.addActionListener(new myActionListener());
tmpB.setActionCommand("last"); for(int i=1; i<=4; ++i){
myPanel tmpP;
pCards.add(""+i, tmpP=new myPanel(i){
public void paint(Graphics g){
g.drawImage(new ImageIcon("zjy"+i+".jpg").getImage(), 20, 0, 300, 400, this);
}
});
tmpP.setBackground(Color.blue);
//tmpP.setSize(new Dimension(300, 400));//tmpP接受了匿名类对象,可以通过这种方法更改匿名类的属性
//这里不设置的原因是它的大小由CardLayout(int hgap, int vgap)决定了
}
add(pBtn, "North");
add(pCards, "Center");
}
class myActionListener implements ActionListener{
public void actionPerformed(ActionEvent e){
String str=e.getActionCommand();
if(str.equals("first"))
Clayout.first(pCards);
else if(str.equals("next"))
Clayout.next(pCards);
else if(str.equals("previous"))
Clayout.previous(pCards);
else if(str.equals("last"))
Clayout.last(pCards);
}
} public static void main(String args[]){
CardLayoutDemo myWindow = new CardLayoutDemo();
myWindow.setSize(new Dimension(600, 600));
myWindow.setResizable(false);
myWindow.addWindowListener(new myClosingListener());
myWindow.setVisible(true);
}
} class myClosingListener extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
} class myPanel extends Panel{
int i;
public myPanel(int i){
this.i=i;
}
}
05-11 16:55