这几天一直在学习Java,在看《Java核心技术》这本书,书中有一个查看动态图片的小程序,写了一下,感觉还挺好使。正好自己电脑没有gif查看器,所以···收藏了。
代码如下:
1 import java.awt.*; 2 import java.io.*; 3 import java.awt.event.ActionEvent; 4 import java.awt.event.ActionListener; 5 import javax.swing.*; 6 7 public class ViewImage { 8 public static void main(String args[]) 9 { 10 EventQueue.invokeLater(new Runnable() 11 { 12 public void run() 13 { 14 JFrame frame = new ViewFrame(); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 frame.setVisible(true); 17 } 18 }); 19 } 20 } 21 22 class ViewFrame extends JFrame 23 { 24 /** 25 * 26 */ 27 private static final long serialVersionUID = 1L; 28 29 public ViewFrame() 30 { 31 setTitle("Image View"); 32 setSize(s_width,s_height); 33 label = new JLabel(); 34 add(label); 35 chooser = new JFileChooser(); 36 chooser.setCurrentDirectory(new File(".")); 37 JMenuBar menubar = new JMenuBar(); 38 setJMenuBar(menubar); 39 JMenu menu = new JMenu("File"); 40 menubar.add(menu); 41 42 JMenuItem openItem = new JMenuItem("Open"); 43 menu.add(openItem); 44 openItem.addActionListener(new ActionListener() 45 { 46 public void actionPerformed(ActionEvent event) 47 { 48 int result = chooser.showOpenDialog(null); 49 if(result == JFileChooser.APPROVE_OPTION) 50 { 51 String name = chooser.getSelectedFile().getPath(); 52 label.setIcon(new ImageIcon(name)); 53 } 54 } 55 }); 56 JMenuItem exitItem = new JMenuItem("Exit"); 57 menu.add(exitItem); 58 exitItem.addActionListener(new ActionListener() 59 { 60 public void actionPerformed(ActionEvent event) 61 { 62 System.exit(0); 63 } 64 }); 65 } 66 67 private JLabel label; 68 private JFileChooser chooser; 69 private static final int s_width = 300; 70 private static final int s_height = 400; 71 }