Java 小程序多次显示自身 [英] Java applet displays itself multiple times

查看:24
本文介绍了Java 小程序多次显示自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为学校制作一个Java小程序,其功能是随机选择六个数字作为三个点的坐标并将它们连接起来形成一个三角形.它只应该绘制一个三角形并找到边长".然而,当我把它放在我的网站上时,它会多次重绘.

I am making a Java applet for school whose function is to randomly select six numbers for coordinates of three points and connect them to make a triangle. It is only supposed to draw one triangle and find the "length of the sides". However when I put it on my website it will redraw itself multiple times.

我制作了另一个小程序,更简单,它只选择 4 个随机数作为坐标来画一条线.同样的问题.

I made another applet, simpler, that only selects 4 random numbers for coordinates to draw a line. Same problem.

重绘问题似乎发生在用户移动屏幕时,例如当我在 Eclipse 中滚动或调整小程序查看器的大小时.我的源代码发布在这里.

The redrawing problem seems to happen when the user moves the screen, e.g. when I scroll or when I resize the applet viewer in Eclipse. My source code is posted here.

感谢您的帮助!谢谢!

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);
    }
}

推荐答案

每次 paint() 被调用时,你都在计算新的坐标.

You are calculating new co-ordinates every time paint() is called.

paint() 每次小程序窗口调整大小或重新获得焦点时都会调用.

paint() is called every time the applet window is resized or regains focus.

要修复,您可以制作

int[] coords = new int[4];

一个类成员变量并移动

coords = randomLine();

到你的 init() 方法,它只会在初始化时调用一次.

to your init() method, which will only be called once upon initialization.

附录:

  • 在覆盖 paint() 时总是调用 super.paint(g);.

对于使用 Swing 的自定义绘画,首选的方法是扩展 JComponent 组件,利用 paintComponent 提供的增强绘画功能.

For custom painting using Swing, the preferred approach is to extends a JComponent component leveraging the enhanced paint functionality offered by using paintComponent.

有关更多信息,请参见:执行自定义绘画.

For more see: Performing Custom Painting.

这篇关于Java 小程序多次显示自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆