嘿,我正在尝试学习如何在java中使用图形,并且正在编写一个非常简单的代码,该代码获取图像并将其在窗口中成一条线移动,当它到达窗口边缘时,它会向下移动几个像素并从另一端开始。
我的问题是我的程序在重新绘制()时没有删除前一个图像,所以我得到了一长串图像,而不是只是移动一个图像(我也遇到了一个奇怪的问题,其中我用来 repaint() 的按钮正在将其图像复制到窗口的左上角,但我认为一次 1 个问题)
这是我正在使用的 2 个类文件的代码:
public class TestieImages extends JFrame implements ActionListener{
ImagePanel jj =new ImagePanel();
TestieImages(){
setTitle("TestFrame");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(582,604);
JButton butt = new JButton("The butt");
butt.addActionListener(this);
butt.setActionCommand("1");
butt.setBounds(200, 200, 80, 24);
add(butt);
add(jj);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String action= e.getActionCommand();
int x=jj.getXCoord();
int y=jj.getYCoord();
if (action.equals("1")){
if (x<=448){
jj.setX(x+64);
}
else{
jj.setX(0);
jj.setY(y+64);
}
jj.repaint();
}
}
public static void main(String[] args) {
JFrame j = new TestieImages();
} }
图像面板
public class ImagePanel extends JPanel{
private int x=0;
private int y=0;
private BufferedImage image;
ImagePanel() {
try {
image = ImageIO.read(new File("C:\\Users\\dleitrim09\\Documents\\NetBeansProjects\\TestieImages\\src\\Resources\\Wall.png"));
} catch (IOException ex) {
// handle exception...
}
}
void setX (int newx){
x=newx;
}
void setY (int newy){
y=newy;
}
int getXCoord (){
return x;
}
int getYCoord (){
return y;
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image, x, y, null);
}
}
这也是输出:
最佳答案
将你的 window 想象成一幅画。当你在上面画一些东西时,你画的是已经存在的东西。因此,如果您只绘制图像,那么您之前绘制的图像仍然保留在那里。
因此,在将图像绘制到窗口之前,您需要“删除 Canvas ”。如果您在调用 drawImage()
之前调用 super.paintComponent(g)
,这将由父类(super class)完成。
关于java - Repaint() 保留原始图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22814456/