我真的很难理解覆盖paintComponent(Graphics g)方法是如何工作的。
我有以下课程:
public class DisplayDocs2 extends JPanel {
ArrayList <BufferedImage> docList;
BufferedImage imageCount;
public DisplayDocs2(ArrayList docList){
this.docList = docList;
}
public JPanel DisplayImage(){
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
for (int i = 0; i < docList.size(); i++){
imageCount = docList.get(i);
}
return this;
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(imageCount, 0, 0, this);
}
}无论我尝试什么,如果我有多个图像,那么第一个图像总是被最后一个图像所覆盖。
我想使用BufferedImage,因为我希望以后能够操作它们。
发布于 2016-01-18 16:06:14
你所经历的行为是你的代码的结果。部分:
for (int i = 0; i < docList.size(); i++) {
imageCount = docList.get(i);
}将imageCount引用设置为paintComponent()方法绘制的列表的最后一个元素。所以你的第一张照片没有覆盖,它根本就没有画。
如果你想画出所有的图像,
for循环和imageCount属性,它们是不必要的。paintComponent()中:
super.paintComponent(g);int x= 0;for (BufferedImage img : docList) { g.drawImage(img,x,0,this);x += img.getWidth();}这将把你所有的图像画在一起。(请注意,如果从未用非空参数调用方法NullPointerException,代码将抛出DisplayDocs2。
发布于 2016-01-18 16:59:22
我真的很难理解覆盖paintComponent(Graphics )方法是如何工作的。
这相当简单。每次系统或您调用JPanel的重绘时,都会执行paintComponent方法中的代码。
在paintComponent方法中,您可以绘制。句号。句号。除了绘制()之外,您在paintComponent方法中什么也不做,什么也不做。
您要做的第一件事是创建一个包含BufferedImage和java.awt.Point的Java对象,以保存BufferedImage的x,y位置。
package com.ggl.testing;
import java.awt.Point;
import java.awt.image.BufferedImage;
public class ImageLocation {
private final BufferedImage image;
private Point imageLocation;
public ImageLocation(BufferedImage image, Point imageLocation) {
this.image = image;
this.imageLocation = imageLocation;
}
public Point getImageLocation() {
return imageLocation;
}
public void setImageLocation(Point imageLocation) {
this.imageLocation = imageLocation;
}
public BufferedImage getImage() {
return image;
}
}接下来,将ImageLocation实例的列表传递给绘图面板。
最后,您的paintComponent方法应该如下所示:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (ImageLocation imageLocation : imageLocations) {
Point p = imageLocation.getImageLocation();
g.drawImage(imageLocation.getImage(), p.x, p.y, this);
}
}您可以在代码中的其他地方创建ImageLocation实例列表。最好是在GUI模型类中。
发布于 2016-01-18 15:47:47
正因如此:
g.drawImage(imageCount, 0, 0, this);试着做某事,如:
g.drawImage(imageCount, x, y, this); // x, y should have dynamic values.希望这能有所帮助。
https://stackoverflow.com/questions/34858484
复制相似问题