图像不会用Java绘制

时间:2015-11-05 21:28:24

标签: java image swing jpanel

所以我正在尝试将图像绘制到JFrame上,并且我使用defualt工具包作为图像观察者,但每次运行项目时都不会绘制图像,但是它会绘制和移动(成功) )我测试的其他形状。

private class Painter extends JPanel implements ImageObserver {

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    Toolkit tk = Toolkit.getDefaultToolkit();
    Image player = tk.createImage("player.jpg");
    tk.prepareImage(player, 50, 50, rootPane);        
    g.setColor(Color.red);
   // g.drawRect(x, y, 50, 50); 
    g.drawImage(player, 200, 200, this);
    window.repaint();            
    }
}

3 个答案:

答案 0 :(得分:3)

你的paintComponent方法不应该做任何涂漆。

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.red);
        // g.drawRect(x, y, 50, 50);
        g.drawImage(player, 200, 200, this);
    }

工具箱和图像行需要在Painter构造函数中。班级名称应以大写字母开头。

根据评论进行编辑:

您编写的代码如下所示:

private Image player;

public Painter() throws Exception {
    player = ImageIO.read(getClass().getResource("player.jpg"));
}

player.jpg需要与源代码位于同一目录中。否则,您的映像目录必须位于Java应用程序的类路径中。

这是一个完整,简单的Swing应用程序,用于在JPanel上绘制图像。

package com.ggl.testing;

import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class MyPanel extends JPanel {

    private static final long serialVersionUID = -9008812738915944216L;

    private static JFrame frame;
    private static MyPanel panel;
    private static Image image;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                image = getImage();
                frame = new JFrame();
                panel = new MyPanel();
                frame.setSize(500, 500);
                frame.add(panel);
                frame.setVisible(true);
            }
        });
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 100, 100, MyPanel.this);
    }

    private static Image getImage() {
        Image image = null;
        try {
            image = ImageIO.read(MyPanel.class.getResource("maze.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}

将maze.jpg更改为您的图像,并将图像放在与此示例代码相同的目录中。

答案 1 :(得分:2)

  1. 不要在绘画方法中进行I / O.绘画方法仅适用于绘画。
  2. 不要在绘画方法中调用repaint()。这将导致无限循环。
  3. 使用ImageIO在类的构造函数中将图像读入类的变量,以便在需要绘制图像时可以使用图像。如果找不到图像,ImageIO将生成一条消息。

答案 2 :(得分:0)

最终代码对于任何有兴趣的人来说都是这样的。之前没有包括动作监听器,因为它与问题大部分无关。包含最后一个片段的原因是公共绘画,因为无法从静态main方法内部调用动作侦听器。这个子类最初是包含所有窗口。*行,但却导致了无数#创建的窗口,所以当它被移动到main时,新的绘制调用必须被封装在受控循环中并且从main方法外部。     Speical感谢所有帮助过我的人,特别是Gilbert Le Blanc

package painting;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.*;
import java.io.*;
import javax.imageio.ImageIO;


/**
 *
 * @author tt700
 */
public class Painting extends JPanel {
    // declaring variables that control movement, show the frame, and make the picture
    int x =50, y =50, counter = 0;
    private static JFrame window = new JFrame("Paint a Picture");
    private static Painting canvas;
    private static Image player;


// main method
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable(){
    @Override
    public void run(){    
    JLabel title = new JLabel("Making a picture frame");
    window.add(title, BorderLayout.NORTH);
    canvas = new Painting();
    window.add(canvas);
    player = getImage("player.jpg");
    window.setVisible(true);
    window.setSize(300,300);
    window.setForeground(Color.red);

    }
   });
}

@Override
// the method that does all the painting
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(player, x, y, Painting.this);
}

// the method that gets a desired image and makes it displayable, with arguments it can be used to swap pictures easily
private static Image getImage(String imagePath){
    Image player = null;
 try{
    player = ImageIO.read(Painting.class.getResource(imagePath));
        }catch(IOException e){
            e.printStackTrace();
        }
      return player; 
}
// the class that controls movement of the picture
public class movement implements KeyListener{   

    @Override
    public void keyTyped(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    // the method that listens to which keys are pressed and acts accordingly
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_RIGHT){                
        x += 5;                
        window.repaint();
    }
    else if(e.getKeyCode() == KeyEvent.VK_LEFT){
        x -= 5;
        window.repaint();
    }
    else if(e.getKeyCode() == KeyEvent.VK_UP){
        y -= 5;
        window.repaint();
    }
    else if(e.getKeyCode() == KeyEvent.VK_DOWN){
        y += 5;
        window.repaint();
    }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }       
}

// the subclass that adds a key listener to the proper component, created since action listeners can't be called in static methods (main)
public Painting(){
    do{
    counter = 1;
    window.addKeyListener(new movement());
    }while(counter < 1);
}

}