load image

package myplane;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImageFileFilterImageScale extends JFrame implements ActionListener {
  Image img;

  JButton getPictureButton  = new JButton("Get Picture");

 
  public ImageFileFilterImageScale() {
    this.setSize(300, 300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel picPanel = new PicturePanel();
    this.add(picPanel, BorderLayout.CENTER);

    JPanel buttonPanel = new JPanel();
    getPictureButton.addActionListener(this);
    buttonPanel.add(getPictureButton);
    this.add(buttonPanel, BorderLayout.SOUTH);

    this.setVisible(true);
  }
  public static void main(String[] args) {
	    new ImageFileFilterImageScale();
	  }

  public void actionPerformed(ActionEvent e) {
    String file = getImageFile();
    if (file != null) {
      Toolkit kit = Toolkit.getDefaultToolkit();
      img = kit.getImage(file);
      img = img.getScaledInstance(300, -1, Image.SCALE_SMOOTH);
      this.repaint();
    }
  }

  private String getImageFile() {
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new ImageFilter());
    int result = fc.showOpenDialog(null);
    File file = null;
    if (result == JFileChooser.APPROVE_OPTION) {
      file = fc.getSelectedFile();
      return file.getPath();
    } else
      return null;
    

  }

  class PicturePanel extends JPanel {
    public void paint(Graphics g) {
      g.drawImage(img, 0, 0, this);
    }
  }

}
class ImageFilter extends javax.swing.filechooser.FileFilter {
  public boolean accept(File f) {
    if (f.isDirectory())
      return true;
    String name = f.getName();
    if (name.matches(".*((.jpg)|(.gif)|(.png))"))
      return true;
    else
      return false;
  }

  public String getDescription() {
    return "Image files (*.jpg, *.gif, *.png)";
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值