gpt4 book ai didi

Java - 使用方法和构造函数绘制图形

转载 作者:行者123 更新时间:2023-11-30 07:23:33 25 4
gpt4 key购买 nike

我正在开发 Java 2d 游戏库。我想要一个名为 paintImage() 的方法在每次调用 paintImage() 时执行 graphics.drawImage()

public void paintImage(image1, x, y){        
//i want it to run graphics.drawImage every time it is called.
}

public void anotherMethod(){
paintImage(...);
paintImage(...);
//paint as many times as i want.
}

public void paintComponent(Graphics graphics){
graphics.drawImage();
super.paintComponents();
}

感谢您的宝贵时间,请提出建议,抱歉,这很难解释。

最佳答案

对于单图显示

public class DrawingDemo {    
private JPanel panel;
private MyImage imageData;

public DrawingDemo() {
...
panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (imageData != null) {
g.drawImage(imageData.getImage(), imageData.getX(), imageData.getY(), this);
}

}
};
...
}

public void paintImage(Image image1, int x, int y) {
imageData = new MyImage(image1, x, y);
panel.repaint();
}

public void anotherMethod() {
paintImage(...);
paintImage(...);
}
}

public class MyImage { // bean class for storing image information
private Image image;
private int x;
private int y;

public MyImage(Image image, int x, int y) {
this.image = image;
this.x = x;
this.y = y;
}

public Image getImage(){
return image;
}

public int getX(){
return x;
}

public int getY(){
return y;
}
... you can add setter methods
}

更新:用于多图显示

    private JPanel panel;
private ArrayList<MyImage> imageData; // or any other data structure you like

public DrawingDemo() {
imageData = new ArrayList<>();
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() {

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (MyImage myImage : imageData) {
g.drawImage(myImage.getImage(), myImage.getX(), myImage.getY(), this);
}
}
};
frame.add(panel);
frame.setVisible(true);

}

public void paintImage(Image image1, int x, int y) {
imageData.add(new MyImage(image1, x, y));
panel.repaint();
}

public void anotherMethod() {
paintImage(new ImageIcon("/home/blackadmin/Desktop/image.jpg").getImage(), 0, 0);
paintImage(new ImageIcon("/home/blackadmin/Desktop/image2.jpg").getImage(), 50, 50);
paintImage(new ImageIcon("/home/blackadmin/Desktop/image3.jpg").getImage(), 100, 100);
}

输出: enter image description here看看这个answer
有不明白的可以留言,希望对你有帮助

关于Java - 使用方法和构造函数绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com