我的项目有问题:/
为什么drawPac无法正常工作。黑色矩形画,但我的图像不是:/为什么
我创建了4个类,这里是3个类的cod,没有扩展JFrame的主类,并且添加了JPanel Game。
档案#1
package pacman;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class Game extends JPanel {
Pac pacman = new Pac();
public void Game() {
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillRect(0, 0,this.getWidth(),this.getHeight());
drawPac(g2d);
}
public void drawPac(Graphics2D g2d){
g2d.drawImage(pacman.image, pacman.x, pacman.y, 100, 100, this);
}
}
档案#2
package pacman;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Actor {
int x,y;
int dv;
Image image;
public void Actor(){
}
}
文件#3
package pacman;
import pacman.Game;
import javax.swing.ImageIcon;
import java.awt.Graphics2D;
public class Pac extends Actor {
public void Pac(){
try{
image = new ImageIcon(Pac.class.getResource("../img/Pac00.gif")).getImage();
x=0;
y=0;
}
catch (Exception e){
System.out.println("Blad prz otwieraniu");
System.exit(0); }
}
}
答案 0 :(得分:2)
1 - “Pac”类应该负责抽奖,你不同意吗?
2 - 对于JPanels和每个JComponent的儿子,你应该覆盖paintComponent方法,而不是paint,它负责将绘画工作委托给paintComponent,paintBorder和paintChildren。您应该调用paintComponent的超级版本,就像在paint中一样。看一下文档。
3 - 在大多数情况下,建议创建一个新的图形上下文(基于原始)。那么,你的行:
Graphics2D g2d = (Graphics2D) g;
应更换为:
Graphics2D g2d = (Graphics2D) g.create();
你需要在使用它之后(在paintComponent的最后一行)处理(g2d.dispose())这个新的上下文。
4 - Pac类的代码是否正确?它在编译吗?图像字段是Actor的成员吗?
我认为您的代码中存在一些您未在问题中显示的问题......
答案 1 :(得分:-1)
好的@lechniak更新游戏类
public class Game extends JPanel {
Pac pacman = new Pac();
public Game() {
setFocusable(true);
setBackground(Color.BLACK);
setDoubleBuffered(true);
}
@Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.black);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
drawPac(g2d);
}
public void drawPac(Graphics2D g2d){
g2d.drawImage(pacman.image, pacman.x, pacman.y, 200, 200, this);
}
public static void main(String[] args) {
JFrame f = new JFrame("Image Draw");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new Game());
f.setSize(350,300);
f.setLocation(300,300);
f.setVisible(true);
}
}
和Pac班
//import javax.swing.ImageIcon;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import java.io.*;
public class Pac /*extends Actor*/ {
int x = 0;
int y = 0;
BufferedImage image;
public Pac() {
try {
image = ImageIO.read(new File("/Users/hlozano/java/swing/programmerBorn.jpg"));
//new ImageIcon(Pac.class.getResource("../img/Pac00.gif")).getImage();
x = 0;
y = 0;
} catch (Exception e) {
System.out.println("Blad prz otwieraniu " + e);
System.exit(0);
}
}
}
图像输出
我希望这些有帮助。