我遇到的问题是图像数组中的第一个图像有时不会被绘制?有什么想法吗?这是我在Java中的代码:gui类有主要方法。我也尝试在GUI类中读取图像并在imagesPanel的构造函数中传递图像。在那种情况下,什么都没有得出。
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel implements MouseMotionListener {
int posX=0;
int posY=0;
ArrayList<Image> images = new ArrayList<Image>();
Image image;
public ImagePanel() {
this.addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
try {
images.add(ImageIO.read(new File("lion.jpeg")));
images.add(ImageIO.read(new File("monkey.jpg")));
} catch (IOException e) {
}
super.paintComponent(g);
for(int i=0;i<images.size();i++){
g.drawImage(images.get(i), posX, posY,100,100, this);
posX=+120;
}
}
@Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
// posX = arg0.getX();
// posY = arg0.getY();
// System.out.println(posX + " " + posY);
// repaint();
}
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class GUI {
public GUI() {
createAndShowGUI();
}
private static void createAndShowGUI() {
JFrame f = new JFrame("Image Viewer");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800, 800);
f.setVisible(true);
ImagePanel imagePanel = new ImagePanel();
f.add(imagePanel);
}
public static void main(String[] args) {
new GUI();
}
}