查找JApplet的宽度和高度

时间:2016-08-10 21:20:42

标签: java graphics jpanel paintcomponent 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);
    }
}

以上内容仍会在JApplet的{​​{1}}框架的右上角生成圆圈,但它应该位于中心位置。

2 个答案:

答案 0 :(得分:2)

问题从这里开始..

Main m = new Main();

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

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

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

应该是:

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

重新小程序:

  1. 为什么编写applet代码?如果是教师指定的,请将其转介至Why CS teachers should stop teaching Java applets
  2. 请参阅Java Plugin support deprecatedMoving to a Plugin-Free Web
  3. 其他提示:

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

      setSize(1000, 500);
      
    2. 这四个属性都在applet的Component超类中定义。 applet继承它们。不要重新定义它们,因为这只会引起混淆。如果默认属性提供所需信息,请使用它们。如果没有,则以不同方式命名您的属性。鉴于他们似乎参与绘制一个圆圈,我建议circleXcircleYcircleWidth& circleHeight

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

答案 1 :(得分:-1)

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
}
}
相关问题