在 Swing JPanel 中移动矩形:原始状态保持不变
我正在尝试制作一个河内塔解算器,它可以简单地解决河内问题而无需任何鼠标事件。问题是,当我移动矩形时,即使在重新绘制之后,原始矩形仍然保留。我在网上搜索并尝试更改代码,但没有任何效果。我正在使用 JFrame,其中包含 JPanel(如果这会改变任何内容)。
我这里有我的磁盘类,它只是一个带有颜色的矩形。
class Disk extends Rectangle {
Color diskColour;
public Disk(int a, int b, int c, int d, Color colour) {
x = a;
y = b;
width = c;
height = d;
diskColour = colour;
}
public Color getColour() {
return diskColour;
}
public void paintSquare(Graphics g) {
repaint();
g.setColor(diskColour);
g.fillRect(x, y, width, height);
repaint();
}
}
下面是我实际调用 PaintSquare 方法的代码:
public void simpleMoveDisk(Disk[] disks, int n, Graphics g) {
disks[n].setLocation(30,25);
disks[n].paintSquare(g);
repaint();
}
paintSquare 方法绘制磁盘,而 setLocation 方法更改其坐标。 当运行时,矩形出现在新位置,但旧位置仍然保留。感谢任何帮助,提前致谢。
I'm trying to make a tower of hanoi solver which simply solves the hanoi without any mouse events. The problem is when I move the rectangle the original remains, even after I repaint. I've searched the net and tried changing the code around but nonthing worked. I am using a JFrame with a JPanel inside of it if that changes anything.
I have my disk class here which is just a rectangle with colour.
class Disk extends Rectangle {
Color diskColour;
public Disk(int a, int b, int c, int d, Color colour) {
x = a;
y = b;
width = c;
height = d;
diskColour = colour;
}
public Color getColour() {
return diskColour;
}
public void paintSquare(Graphics g) {
repaint();
g.setColor(diskColour);
g.fillRect(x, y, width, height);
repaint();
}
}
Here is my code where I actually call the paintSquare method:
public void simpleMoveDisk(Disk[] disks, int n, Graphics g) {
disks[n].setLocation(30,25);
disks[n].paintSquare(g);
repaint();
}
The paintSquare method paints the disk, while the setLocation method changes its coordinates.
When this runs the rectangle occurs in the new location, however the old one still remains. Any help is appreciated, thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在多个地方调用了 repaint() ,但您不应该这样做。
让你的顶级类进行绘画,调用paintSquare方法和任何其他需要的方法。这些方法不应该调用 repaint()。
另外,您的简单移动磁盘确实很奇怪,因为它传递了一个磁盘数组、一个索引和一个图形对象。相反,让它只接受磁盘。只需将数组中需要更新的那个传递给它即可。然后让调用 simpleMoveDisk 的任何类单独调用 repaint,而不是尝试在同一方法中绘制和更新模型。
You are calling repaint() in several places and you shouldn't be.
Have your the top level class that is doing the painting, call the paintSquare method and any other method that is needed. Those methods should not be calling repaint().
Also your simple move disk is really strange in the fact that it passes an array of Disks, an index, and a graphics object. Instead make it just take in a Disk. Just pass it the one out of the array that is needed to be updated. Then let whatever class that calls simpleMoveDisk, separately make a call to repaint instead of trying to paint and update the model in the same method.