写一个简单的图片浏览器:
package day14; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class ImageBorwer extends JFrame{ /** 图片浏览中的卡片布局 **/ private CardLayout lyCard; /** 装有7个标签的面板 **/ private JPanel pnShow; public ImageBorwer(){ JPanel pnBasic = new JPanel(); pnBasic.setLayout(new BorderLayout()); // 定义用于显示图片的小面板 pnShow = new JPanel(); lyCard = new CardLayout(); pnShow.setLayout(lyCard); JLabel[] lbArrShow = new JLabel[7]; for(int i=0;i<lbArrShow.length;i++){ // 初始化标签 lbArrShow[i] = new JLabel(); // 给标签添加图片 // 图片路径从工程开始。 ImageIcon icon = new ImageIcon("fff/role1/"+(i+1)+".png"); lbArrShow[i].setIcon(icon); pnShow.add(i+"",lbArrShow[i]); } pnBasic.add(pnShow,BorderLayout.CENTER); // 定义操作区按钮的小面板 JPanel pnOpr = new JPanel(); // 指定该面板布局为1行3列 pnOpr.setLayout(new GridLayout(1,3)); String[] strArr = {"上一个","首页","下一个"}; JButton[] btnArr = new JButton[strArr.length]; for(int i=0;i<strArr.length;i++){ btnArr[i] = new JButton(strArr[i]); // 给每一个按钮添加监听 btnArr[i].addActionListener(new ButtonMonitor()); pnOpr.add(btnArr[i]); } pnBasic.add(pnOpr,BorderLayout.SOUTH); // 绑定 setContentPane(pnBasic); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("图片浏览"); // setSize setLocation ImageIcon icon = new ImageIcon("fff/icon24.png"); Image image = icon.getImage(); setIconImage(image); setBounds(200,200,400,300); pack(); // 窗体可见 setVisible(true); } private class ButtonMonitor implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { JButton btnClick = (JButton) e.getSource(); String strBtnTxt = btnClick.getText(); if("上一个".equals(strBtnTxt)){ // Iterator next()-->ListIterator next() privious(); lyCard.previous(pnShow); } else if("下一个".equals(strBtnTxt)){ // Iterator next()-->ListIterator next() privious(); lyCard.next(pnShow); }else if("首页".equals(strBtnTxt)){ // Iterator next()-->ListIterator next() privious(); // lyCard.first(pnShow); // 取出指定名字的标签 lyCard.show(pnShow, 3+""); } } } public static void main(String[] args) { new ImageBorwer(); } }
效果显示: