Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to relocate the applet viewer window?

Tags:

java

applet

using Eclipse to make java Applet. Every time to run it from the IDE, the applet viewer is shown on left top corner at (0,0). How to programmably change it to the middle of screen during the development? I know when deploy in browser, we can't change the window from inside the applet since the html determines the location.

like image 623
Hai Bi Avatar asked May 15 '12 12:05

Hai Bi


People also ask

How do I fix an applet window in Java?

Re-launch the web browser. Go to the Java applet. When the "Security Warning" window asking "Do you want to run this application?" appears, if there is a "I accept the risk and want to run this app." option, checkmark it ON first then --> Click the "Run" button. The Java applet should load OK now.


1 Answers

In contrast to the other poster, I think this is a pointless exercise and prefer their suggestion to make an hybrid application/applet to make development easier.

OTOH - 'we have the technology'. The top-level container of an applet in applet viewer is generally a Window. Get a reference to that, and you can set it where you wish.

Try this (irritating) little example.

// <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);
        }
    }
}
like image 70
Andrew Thompson Avatar answered Sep 25 '22 03:09

Andrew Thompson