如何重新定位applet查看器窗口?

Hai*_* Bi 7 java applet

使用Eclipse制作Java Applet.每次从IDE运行它时,applet查看器显示在左上角的(0,0)处.如何在开发过程中可编程地将其更改为屏幕中间?我知道在浏览器中部署时,我们无法从applet内部更改窗口,因为html确定了位置.

And*_*son 7

与其他海报相比,我认为这是一个毫无意义的练习,并且更喜欢他们建议制作混合应用程序/小程序以使开发更容易.

OTOH - '我们有技术'.applet查看器中applet的顶级容器通常是Window.获取对它的引用,您可以将它设置在您希望的位置.

尝试这个(刺激性的)小例子.

// <applet code=CantCatchMe width=100 height=100></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class CantCatchMe extends JApplet {

    Window window;
    Dimension screenSize;
    JPanel gui;
    Random r = new Random();

    public void init() {
        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                moveAppletViewer();
            }
        };
        gui = new JPanel();
        gui.setBackground(Color.YELLOW);
        add(gui);

        screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        // change 2000 (every 2 secs.) to 200 (5 times a second) for REALLY irritating!
        Timer timer = new Timer(2000, al);
        timer.start();
    }

    public void start() {
        Container c = gui.getParent();
        while (c.getParent()!=null) {
            c = c.getParent();
        }
        if (c instanceof Window) {
            window = (Window)c;
        } else {
            System.out.println(c);
        }
    }

    private void moveAppletViewer() {
        if (window!=null) {
            int x = r.nextInt((int)screenSize.getWidth());
            int y = r.nextInt((int)screenSize.getHeight());
            window.setLocation(x,y);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)