使用java swing插入图像

时间:2017-03-14 16:27:48

标签: java

我正在尝试将图像插入资源文件夹并使用它在框架中显示。但是我收到了这个错误:

  

类型不匹配:无法从java.awt.Image转换为project.image

2 个答案:

答案 0 :(得分:2)

以下是使用默认java资源中的图像图标的示例。

    JLabel lblNewLabel = new JLabel("");
    lblNewLabel.setIcon(new ImageIcon(test.class.getResource("/com/sun/java/swing/plaf/windows/icons/Question.gif")));
    lblNewLabel.setBounds(112, 60, 151, 126);
    frmTitle.getContentPane().add(lblNewLabel);

上面的代码会在您的应用上添加问号图像,例如MDN Event.target。您当然可以将其更改为您想要的任何内容。

答案 1 :(得分:0)

希望这个简单的样本可以帮助你...

import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
import java.awt.EventQueue;
import javax.swing.JFrame;

public class FloorPlaner extends JFrame {
     protected BufferedImage wall;

     public FloorPlaner(){ 
          super("FloorPlaner");
          try {
          wall = ImageIO.read(new File ("wall.png")); //Load a wall
          } catch(IOException bug) { //Create a wall image
          wall=new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);
          Graphics2D wg=wall.createGraphics();
          wg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
          wg.setColor(Color.BLACK);
          wg.fillRect(0,0,20,20);
          System.out.println(bug);
          }

          requestFocus(); 

          setContentPane(new DrawingPane());

          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

          setSize(400, 400);

          setResizable(true); 

          setVisible(true); 

          while (true) { 
              repaint();
              try {
              Thread.sleep(40); //25 FPS
              } catch(InterruptedException bug) {
              Thread.currentThread().interrupt();
              System.out.println(bug);
              }
          }
     }


     class DrawingPane extends JPanel { //Where you actually draw on
        public void paintComponent(Graphics g) { //Drawing method
           g.drawImage(wall,0,0,null);
        }   
     }
     public static void main(String args[]) {
            new FloorPlaner(); //Start it
     }
}