简体   繁体   English

图形无法正确清除

[英]Graphics wont clear properly

I am having problems, I want a square (fly) to be drawn and redrawn to show movement. 我遇到了问题,我想绘制一个正方形(苍蝇)并重新绘制它以显示运动。 Fine in this code when the button is pressed the fly does "move", but the old squares do not delete. 当按下按钮时,此代码中的代码会“移动”,但旧的正方形不会删除。 I have tried enviromentPanel.repaint() updateui() and removeall() and I cannot get it to work, if I use any of them then none of the shapes appear and I get a blank screen. 我已经尝试过enviromentPanel.repaint()updateui()和removeall(),但我无法使用它,如果我使用其中任何一个,则不会出现任何形状,并且出现黑屏。

import java.util.Random;


public class Fly implements Runnable{
private int xPosition;
private int yPosition;
private boolean eaten;

public Fly(){
    Random randomGenerator = new Random();
    xPosition = randomGenerator.nextInt(690) + 10;
    yPosition = randomGenerator.nextInt(690) + 10;
    eaten = false;
}

public int getxPosition() {
    return xPosition;
}

public void setxPosition(int xPosition) {
    this.xPosition = xPosition;
}

public int getyPosition() {
    return yPosition;
}

public void setyPosition(int yPosition) {
    this.yPosition = yPosition;
}

public boolean isEaten() {
    return eaten;
}

public void setEaten(boolean eaten) {
    this.eaten = eaten;
}

public void move(){
      Random randomGenerator = new Random();

        int xChange = -10 + randomGenerator.nextInt(20);
        int yChange = -10 + randomGenerator.nextInt(20);
        xPosition = xPosition + xChange;
        yPosition = yPosition + yChange;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        move();

}

@Override
public String toString() {
    return "Fly [xPosition=" + xPosition + ", yPosition=" + yPosition
            + ", eaten=" + eaten + "]";
}

@Override
public void run() {
    move();
}


}

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.*;
import javax.imageio.ImageIO;

public class Enviroment2 implements Runnable,ActionListener{ 
private JFrame frame;
private JPanel enviromentPanel,totalGUI,enviromentButtonPanel;
private JButton newFrogButton, resetButton, hungryButton;
private JTextField enterName;
private JLabel hungryLabel;
private ArrayList<Frog> frogs;
private ArrayList<Fly> flys;



public Enviroment2(){
totalGUI = new JPanel();
flys = new ArrayList<Fly>();
frogs = new ArrayList<Frog>();
enviromentPanel = new JPanel();
enviromentButtonPanel = new JPanel();
newFrogButton = new JButton("New Frog");
enterName = new JTextField("Enter name");

hungryButton = new JButton("Hungry!");

resetButton = new JButton("Reset");
frame = new JFrame("[=] Hungry Cyber Pet [=]");
JFrame.setDefaultLookAndFeelDecorated(true);

frame.setContentPane(runEnviroment());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(740, 800);
frame.setVisible(true);



}



public JPanel runEnviroment(){

totalGUI.setLayout(null);

enviromentPanel.setLayout(null);
enviromentPanel.setLocation(10, 10);
enviromentPanel.setSize(700, 700);
enviromentPanel.setBackground(Color.WHITE);
totalGUI.add(enviromentPanel);


FlowLayout experimentLayout = new FlowLayout();
enviromentButtonPanel.setLayout(experimentLayout);
enviromentButtonPanel.setLocation(10, 710);
enviromentButtonPanel.setSize(700, 50);
totalGUI.add(enviromentButtonPanel);

newFrogButton.setLocation(0, 0);
newFrogButton.setSize(120, 30);
newFrogButton.addActionListener(this);
enviromentButtonPanel.add(newFrogButton);

enterName.setLocation(140,0);
enterName.setSize(120,30);
enviromentButtonPanel.add(enterName);

hungryButton.setLocation(280, 0);
hungryButton.setSize(120, 30);
hungryButton.addActionListener(this);
enviromentButtonPanel.add(hungryButton);

resetButton.setLocation(420, 0);
resetButton.setSize(120, 30);
resetButton.addActionListener(this);
enviromentButtonPanel.add(resetButton);


totalGUI.setOpaque(true);

return totalGUI;
}


public void draw(){     

Graphics paper = enviromentPanel.getGraphics();

for (int i = 0; i <= flys.size()-1; i++){
    System.out.println("hi");
    paper.setColor(Color.BLACK);

    paper.fillRect(flys.get(i).getxPosition(), flys.get(i).getyPosition(), 10,      10);




}
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

draw();

}

public void actionPerformed(ActionEvent e) {
 if(e.getSource() == newFrogButton){
     Frog frog = new Frog(enterName.getText());
     frogs.add(frog);
     Fly fly = new Fly();
     Thread t = new Thread(fly);
     t.start();
     flys.add(fly);
     showFlys();

  }
  else if(e.getSource() == hungryButton){
  }
  else if(e.getSource() == resetButton){
      frogs.clear();
      flys.clear();
      System.out.println(frogs);
      System.out.println(flys);


  }
}


public void showFlys(){
for (int i = 0; i <= flys.size()-1; i++){
    System.out.println(flys.get(i));
}

}



@Override
public void run() {
draw(); 
}



}

This Graphics paper = enviromentPanel.getGraphics() is the start of your problems, this is not how custom painting is done. Graphics paper = enviromentPanel.getGraphics()是问题的开始,这不是完成自定义绘制的方式。

getGraphics returns the graphics context that was used in the last paint cycle, at best it's a snap shot, at worst it can be null . getGraphics返回在上一个绘制周期中使用的图形上下文,最好是快照,最坏时可以为null

You should never maintain a reference to any Graphics context you didn't create. 您永远不应维护对未创建的任何Graphics上下文的引用。 They can change and painting on it out of turn can produce unexpected results. 他们可以更改,并在其上绘画会产生意想不到的结果。

Instead, you should override the paintComponent method (probably in environmentPanel ) and do all your custom painting in it. 相反,您应该重写paintComponent方法(可能在environmentPanel )并在其中进行所有自定义绘制。

Your second problem is your violating the thread rules of Swing - you should never create or modify any UI component in any thread other then the EDT 第二个问题是您违反了Swing的线程规则-除EDT之外,您不应在任何线程中创建或修改任何UI组件

You might like to take a read through 您可能想通读一遍

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM