www.pudn.com > SwingPic.rar > SwingPic.java


import java.awt.Container; 
import java.awt.Dimension; 
import java.awt.Event; 
import java.awt.FileDialog; 
 
//import java.awt.Image; 
import java.awt.Menu; 
import java.awt.MenuBar; 
import java.awt.MenuItem; 
 
//import java.awt.Toolkit; 
//import java.awt.event.WindowAdapter; 
//import java.awt.event.WindowEvent; 
import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JScrollPane; 
import javax.swing.SwingConstants; 
import javax.swing.UIManager; 
 
 
public class SwingPic extends JFrame { 
    String lastDir; 
    protected ImageIcon iImage; 
    int height; 
    int width; 
    JLabel labeledPic; 
    JScrollPane scroller; 
    Container content; 
 
    public SwingPic() { 
        try { 
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
        } catch (Exception e) { 
        } 
 
        // End program when window closes 
        /*addWindowListener(new WindowAdapter() { 
            public void windowClosing(WindowEvent e) { 
                System.exit(0); 
            } 
        });*/ 
        setTitle("图像浏览"); 
 
        MenuBar mbar = new MenuBar(); 
        Menu m = new Menu("文件"); 
        m.add(new MenuItem("打开")); 
        m.add(new MenuItem("退出")); 
        mbar.add(m); 
        setMenuBar(mbar); 
        setSize(800, 600); 
 
        labeledPic = new JLabel(); 
        labeledPic.setHorizontalAlignment(SwingConstants.CENTER); 
        scroller = new JScrollPane(labeledPic); 
        content = getContentPane(); 
        content.add(scroller); 
        this.show(); 
    } 
 
    public boolean action(Event evt, Object arg) { 
        if (arg.equals("打开")) { 
            FileDialog fileDd = new FileDialog(this, "打开图像", FileDialog.LOAD); 
            fileDd.setFile("*.gif;*.jpg"); 
            fileDd.setDirectory(lastDir); 
            fileDd.show(); 
 
            String picName = fileDd.getFile(); 
            lastDir = fileDd.getDirectory(); 
 
            if (picName != null) { 
                iImage = new ImageIcon(lastDir + picName); 
                height = iImage.getIconHeight(); 
                width = iImage.getIconWidth(); 
 
                //System.out.println("new image icon" + height + " " + width); 
            } 
 
            //System.out.println("new file" + lastDir + picName); 
            labeledPic.setIcon(iImage); 
 
            scroller.setPreferredSize(new Dimension(height, width)); 
 
            //scroller.setSize(77, 49); 
        } else if (arg.equals("退出")) { 
            System.exit(0); 
        } else { 
            return false; 
        } 
 
        return true; 
    } 
 
    public static void main(String[] args) { 
        SwingPic app = new SwingPic(); 
 
        //app.show(); 
    } 
}