我的代码是关于创建具有随机颜色和随机直径的圆圈,然后将所有圆圈信息保存到文本文件中,这样当我将来执行程序时,我会找到我过去创建的所有圆圈,所以我创建了一个包含所有圆形信息x和y直径颜色以及dx和dy的圆类,因为“我将在未来使用java swing timer移动这些圆圈” 我还创建了一个View类和控制器类以及WriteFile类,我面临的问题是当我在paintComponent()方法中调用saveCircles()方法时,它会在我的文本文件中重复循环,即使我已将我的圆圈添加到hashSet和我也覆盖了equals()和hashCode()
查看class`public class View extends JPanel { 控制器控制器=新控制器(); HashSet myCircleHashSet = new HashSet<>();
public View() {
this.addMouseListener(controller);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
myCircleHashSet = controller.getMyCircleSet();
for (MyCircle myCircle : this.myCircleHashSet) {
paintCircle(g, myCircle);
}
repaint();
saveCircle();
}
public void paintCircle(Graphics graphics, MyCircle myCircle) {
graphics.setColor(myCircle.color);
graphics.fillOval(myCircle.x, myCircle.getY(), myCircle.a, myCircle.b);
}
public void saveCircle() {
System.out.println(this.myCircleHashSet.size());
try {
new WriteFile(myCircleHashSet);
} catch (IOException e) {
e.printStackTrace();
}
}`
控制器类
public class Controller implements MouseListener {
private HashSet<MyCircle> myCircleSet = new HashSet<>();
private int r, g, b, d;
@Override
public void mousePressed(MouseEvent e) {
r = new Random().nextInt(256);
g = new Random().nextInt(256);
b = new Random().nextInt(256);
d = 10 + new Random().nextInt(100);
myCircleSet.add(new MyCircle(e.getX() - d / 2, e.getY() - d / 2, d, d, new
Color(r, g, b), 0, 0));
}
public HashSet<MyCircle> getMyCircleSet() {
return myCircleSet;
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
WriteFile类
public class WriteFile {
FileWriter fileWriter;
PrintWriter pw;
HashSet<MyCircle> circleHashSet;
public WriteFile(HashSet<MyCircle> circleHashSet) throws IOException {
this.circleHashSet = circleHashSet;
fileWriter = new FileWriter("test.txt",true);
pw = new PrintWriter(fileWriter);
for (MyCircle circle:circleHashSet) {
pw.println(circle);
}
pw.close();
fileWriter.close();
}
答案 0 :(得分:0)
我面临的问题是,当我在paintComponent()方法中调用saveCircles()方法时,它会在我的文本文件中重复循环,即使我已将我的圆圈添加到hashSet中并且我也覆盖了equals()和hashCode()方法
paintComponent()方法仅用于绘画。该方法中应该没有程序逻辑。您无法控制paintComponent()方法被调用的时间或频率。
创建圆圈或更改圆圈的属性时,应将圆圈写入文件。或者,您需要添加逻辑以在关闭程序时保存程序的状态。
repaint();
永远不要在paintComponent()方法中调用repaint()。这将造成一个浪费CPU的连续循环。
答案 1 :(得分:0)
非常感谢camickr我终于通过添加一个像这样的窗口监听器解决了这个问题:
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent windowEvent) {
super.windowClosing(windowEvent);
view.saveCircle();
}
});
我已将repaint()添加到mouseListener事件
@Override
public void mousePressed(MouseEvent e) {
r = new Random().nextInt(256);
g = new Random().nextInt(256);
b = new Random().nextInt(256);
d = 10 + new Random().nextInt(100);
myCircleSet.add(new MyCircle(e.getX() - d / 2, e.getY() - d / 2,
d, d, new
Color(r, g, b), 0, 0));
view.repaint();
}