JavaApplet 在屏幕上打印额外的圆圈 [英] JavaApplet extra circles printing on screen

查看:15
本文介绍了JavaApplet 在屏幕上打印额外的圆圈的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手.我试图在 javaApplet 中绘制一个圆圈,但不知何故在输出中它显示了 3 个圆圈.任何的想法?

I am new in this. I am trying to draw a circle in a javaApplet but somehow in the output it shows 3 circles. Any idea?

import javax.swing.JApplet;
import java.util.*;
import java.awt.*;

public class Shapes extends JApplet
{
    public void paint (Graphics page)
    {
        resize(400,300);
        Random rand = new Random();

        // Declare size constants
        final int circleMax = 160,circleMin = 40; // circle max and min diameter
        final int locMaxX = 360, locMaxY = 260;
        int radiusSize = 0, locationx = 0,locationy = 0 ;

        // Declare variables
        radiusSize = (rand.nextInt(circleMax)+ circleMin); 
        locationx =20 ;//rand.nextInt(locMaxX)+ 20;
        locationy =20 ;// rand.nextInt(locMaxY) + 20;

        // Draw the circle 1
        page.drawOval(locationx, locationy, radiusSize,radiusSize);
    }
}

推荐答案

您的主要问题是您在绘制方法中调用 resize(...) 而不是调用超级的绘制方法.话虽如此,我的建议是:

Your main problems are that you're calling resize(...) within a painting method and are not calling the super's painting method. Having said that, my recommendations are:

  • 切勿在顶级窗口(例如 JApplet 或 JFrame 的)的绘制方法中进行绘制.
  • 而是在顶级窗口中显示的 JPanel 的paintComponent 方法中绘制.
  • 在你的绘画方法中调用 super 的方法,通常是先调用.

例如

import javax.swing.JApplet;
import java.util.*;
import java.awt.*;

public class Shapes extends JApplet {

    @Override
    public void init() {
        add(new ShapesPanel());
    }

}    

class ShapesPanel extends JPanel {
    private Random rand = new Random();
    // Declare size constants
    final int circleMax = 160,circleMin = 40; // circle max and min diameter
    final int locMaxX = 360, locMaxY = 260;
    int radiusSize = 0, locationx = 0,locationy = 0 ;

    public ShapesPanel() {
        radiusSize = (rand.nextInt(circleMax)+ circleMin); 
        locationx =20 ;//rand.nextInt(locMaxX)+ 20;
        locationy =20 ;// rand.nextInt(locMaxY) + 20;
    }

    @Override
    protected void paintComponent (Graphics page)   {
        super.paintComponent(page);
        // Draw the circle 1
        page.drawOval(locationx, locationy, radiusSize,radiusSize);
    }
}

这篇关于JavaApplet 在屏幕上打印额外的圆圈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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