黑马程序员技术交流社区

标题: 怎么用java读取电脑中的图片然后在JFrame中显示出来? [打印本页]

作者: 张奇云    时间: 2011-11-3 07:49
标题: 怎么用java读取电脑中的图片然后在JFrame中显示出来?
怎么用java读取电脑中的图片然后在JFrame中显示出来?
作者: fso918    时间: 2011-11-3 09:10
给段代码给你:
我自己用的。
  1. class ImagePanel extends JPanel {
  2.         private static final long serialVersionUID = 1L;
  3.         JPanel contentPanel;
  4.         BorderLayout bl = new BorderLayout();
  5.         DrawCanvas canvas = new DrawCanvas();

  6.         ImagePanel(){
  7.                 init();
  8.         }
  9.        
  10.         private void init() {
  11.                 contentPanel = this;
  12.                 contentPanel.setLayout(bl);
  13.                 this.setSize(new Dimension(330, 432));
  14.                 contentPanel.add(this.canvas, BorderLayout.CENTER);
  15.         }

  16.          

  17.         class DrawCanvas extends Canvas {
  18.                 private static final long serialVersionUID = 1L;
  19.                 Image image;

  20.                 public DrawCanvas() {
  21.                         image = this.getToolkit().getImage("images//zhenji.jpg");
  22.                         MediaTracker mt = new MediaTracker(this);
  23.                         mt.addImage(image, 1);
  24.                         try {
  25.                                 mt.waitForAll();
  26.                         } catch (InterruptedException e) {
  27.                                 e.printStackTrace();
  28.                         }
  29.                         if (image.getWidth(this) == -1) {
  30.                                 System.out.println("Could not get the image");
  31.                                 System.exit(-1);
  32.                         }
  33.                         this.setBackground(Color.black);
  34.                 }
  35.                 @Override
  36.                  public void paint(Graphics g){
  37.                          Graphics2D g2D = (Graphics2D)g;
  38.                         BufferedImage bimage = (BufferedImage)this.createImage(this.getWidth(),this.getHeight());
  39.                         bimage.createGraphics().drawImage(this.image,0,0,this);
  40.                         g2D.drawImage(bimage,0,0,this);
  41.                  }
  42.         }
  43. }
复制代码

作者: 张奇云    时间: 2011-11-3 10:41
谢谢,学习了




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2