查找 JApplet 的宽度和高度

Finding the width and height of a JApplet

我正在寻找 JApplet 的宽度和高度。我尝试了不同的方法并寻找答案,但还没有找到答案。

下面是代码的主要部分:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.Timer;

public class Main extends JApplet implements ActionListener {
    private static final long serialVersionUID = 1L;

    Timer timer;
    public int x, y, width = 40, height = 40;

    public void init() {
        Painter painter = new Painter();
        JApplet component = new JApplet();
        x = (component.getWidth())/2 - (width/2) - 20;
        y = (component.getHeight())/2 - (height/2) - 40;

        painter.setBackground(Color.white);
        setContentPane(painter);
        setSize(1000, 500);
    }

    public void start() {
        if (timer == null) {
            timer = new Timer(100, this);
            timer.start();
        } else {
            timer.restart();
        }
    }

    public void stop() {    
        if (timer != null) {
            timer.stop();
            timer = null;
        } 
    }

    public void actionPerformed(ActionEvent ae) {
        repaint();
    }
}

下面是画圆的代码:

import java.awt.Graphics;
import javax.swing.JPanel;

public class Painter extends JPanel {
    private static final long serialVersionUID = 2L;

    Main m = new Main();

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawOval(m.x, m.y, m.width, m.height);
    }
}

上面仍然在 0,0 处的 JApplet 框架的右上角生成圆圈,但它应该在中心。

JFrame 对此有更好的实现。

public class Main extends JFrame {

public static void main(String[] args) {
    setSize(500, 500);
    setVisible(true);
    setLayout(new FlowLayout()); // THIS LINE IS IMPORTANT
    // Put rest of code here :D
}
}

问题从这里开始..

Main m = new Main();

这是一个新的小程序,从未在屏幕上显示并且(默认)大小为 0 x 0 像素。

这里正确的做法是完全忽略父容器。相关的只是进行自定义绘画的面板的大小。所以..

 g.drawOval(m.x, m.y, m.width, m.height);

应该是:

g.drawOval(0, 0, getWidth(), getHeight());

重新小程序:

  1. 为什么要编写小程序?如果是老师指定的,请参考Why CS teachers should stop teaching Java applets
  2. Java Plugin support deprecated and Moving to a Plugin-Free Web

其他提示:

  1. 任何小程序都不应尝试调整自身大小。大小在启动它的 HTML 中设置,因此请删除此行。

    setSize(1000, 500);
    
  2. 这四个属性都是在小程序的Componentsuperclass中定义的。小程序继承了它们。不要重新定义它们,因为那样只会造成混乱。如果默认属性提供了所需的信息,请使用它们。如果不是,则以不同方式命名您的属性。鉴于他们似乎参与画圈,我建议circleXcircleYcircleWidth & circleHeight.

    public int x, y, width = 40, height = 40;