我正在为学校制作一个Java小程序,其功能是随机选择六个数字作为三个点的坐标并将它们连接成一个三角形。它只应该画一个三角形并找到“边长”。然而,当我把它放在我的网站上时,它会多次重绘自己。
我又做了一个小程序,比较简单,只取4个随机数作坐标画线。同样的问题。
重绘问题似乎发生在用户移动屏幕时,例如当我在 Eclipse 中滚动或调整小程序查看器大小时。我的源代码发布在这里。
感谢您的帮助!谢谢!
import javax.swing.JApplet;
import java.awt.*;
@SuppressWarnings("serial")
public class LineApplet extends JApplet {
/**
* Create the applet.
*/
static int width;
int height;
public void init() {
width = getSize().width;
height = getSize().height;
}
public static int[] randomLine() {
int[] pointArray = new int[4];
int x;
for (int i = 0; i < 4; i++) {
x = ((int)(Math.random()*(width/10-2)))*20+10;
pointArray[i] = x;
}
return pointArray;
}
public void paint(Graphics g) {
g.setColor(Color.blue);
int[] coords = new int[4];
coords = randomLine();
g.drawLine(coords[0], coords[1], coords[2], coords[3]);
g.drawString(coords[0]/10 + ", " + coords[1]/10, coords[0], coords[1]);
g.drawString(coords[2]/10 + ", " + coords[3]/10, coords[2], coords[3]);
int midpointx = (coords[0] + coords[2])/2;
int midpointy = (coords[1] + coords[3])/2;
g.drawString(midpointx/10 + ", " + midpointy/10, midpointx, midpointy);
}
}
最佳答案
正如 Reimues 所指出的,每次重新绘制小程序时,您都在重新生成坐标。
您的 paint
方法的另一个问题实际上是您不清楚图形上下文的先前状态(这本来可以由 paint
完成,但您失败了当您覆盖它时尊重它的功能)。
你有两个选择。
- 调用
super.paint(g)
- 调用
super.paint(g)
并调用Graphics#clearRect(int, int, int, int)
或Graphics#fillRect(int, int, int, int)
您还应该(在极少数情况下)需要重写顶级容器的 paint
方法。原因之一是它们不是双缓冲的,另一个原因是绘制链复杂且容易损坏...
您最好使用 JPanel
(或类似的)并覆盖 paintComponent
方法...
已更新
我更新了您的代码以演示这些问题。
public class TestBadApplet extends JApplet {
public void init() {
}
@Override
public void start() {
final LinePane linePane = new LinePane();
setLayout(new BorderLayout());
JButton update = new JButton("Update");
add(linePane);
add(update, BorderLayout.SOUTH);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
linePane.regenerate();
}
});
}
protected class LinePane extends JPanel {
private int[] coords = new int[4];
public void regenerate() {
coords = randomLine();
repaint();
}
public int[] randomLine() {
int[] pointArray = new int[4];
int x;
for (int i = 0; i < 4; i++) {
x = ((int) (Math.random() * (Math.min(getWidth(), getHeight()) / 10 - 2))) * 20 + 10;
pointArray[i] = x;
}
return pointArray;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.blue);
g.drawLine(coords[0], coords[1], coords[2], coords[3]);
g.drawString(coords[0] / 10 + ", " + coords[1] / 10, coords[0], coords[1]);
g.drawString(coords[2] / 10 + ", " + coords[3] / 10, coords[2], coords[3]);
int midpointx = (coords[0] + coords[2]) / 2;
int midpointy = (coords[1] + coords[3]) / 2;
g.drawString(midpointx / 10 + ", " + midpointy / 10, midpointx, midpointy);
}
}
}
使用super.paintComponent
没有super.paintComponent
关于Java 小程序多次显示自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13168078/