JAVA打开图片(面板自动随图片大小调整)

使用JAVA打开图片。(面板可以随着图片的不同,调整不同的大小去展示图片)


JAVA代码:

public class ShowPic {
	
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        EventQueue.invokeLater(new Runnable() {
            
            @Override
            public void run() {
                // TODO Auto-generated method stub
                JFrame frame = new ImageViewerFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }
}

class ImageViewerFrame extends JFrame{
    public ImageViewerFrame(){
        setTitle("ImageViewer");
        setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        label = new JLabel();
        add(label);
        chooser = new JFileChooser();
        JMenuBar menubar = new JMenuBar();
        setJMenuBar(menubar);
        JMenu menu = new JMenu("File");
        menubar.add(menu);
        JMenuItem openItem = new JMenuItem("Open");
        menu.add(openItem);
        JMenuItem exitItem = new JMenuItem("Close");
        menu.add(exitItem);
	this.setLocation(screen.width/2-this.getWidth()/2,screen.height/2-this.getHeight()/2);
        openItem.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                int result = chooser.showOpenDialog(null);
                if(result == JFileChooser.APPROVE_OPTION){
                    String name = chooser.getSelectedFile().getPath();
                    File picture = new File(name);
                    BufferedImage sourceImg = null;
					try {
						sourceImg = ImageIO.read(new FileInputStream(picture));
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                    setSize(sourceImg.getWidth(),sourceImg.getHeight());
                    setLocation(screen.width/2-sourceImg.getWidth()/2,screen.height/2-sourceImg.getHeight()/2);
                    label.setIcon(new ImageIcon(name));
                }
            }
        });
        exitItem.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub
                System.exit(0);
            }
        });
    }
    Toolkit tool = Toolkit.getDefaultToolkit();
    Dimension screen = tool.getScreenSize();
    private JLabel label;
    private JFileChooser chooser;
    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 400;
}


图一:

JAVA打开图片(面板自动随图片大小调整)_第1张图片

图二:
JAVA打开图片(面板自动随图片大小调整)_第2张图片
图三:

JAVA打开图片(面板自动随图片大小调整)_第3张图片

图四:

JAVA打开图片(面板自动随图片大小调整)_第4张图片

你可能感兴趣的:(JAVA自学,不积跬步无以至千里)