How to move the applet viewport?

using Eclipse to create a java applet. Each time you launch it from the IDE, the applet viewer is displayed in the upper left corner (0,0). How to program it in the middle of the screen during development? I know that when deploying in a browser, we cannot change the window from inside the applet, since html determines the location.

+7
source share
2 answers

Unlike another poster, I think this is a meaningless exercise and prefers their proposal to make a hybrid application / applet to facilitate development.

OTOH - "we have the technology." The applet's top-level container in the applet viewer is usually Window . Get a link to this and you can install it wherever you want.

Try this (annoying) 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); } } } 
+7
source

Interest Ask.

I did not find a reliable way to affect the AppletViewer, not without using a script on Windows to run it from batch file mode, and even that did not work.

An alternative is to write test code so that the applet runs in a JFrame, which you can easily center.

Add the main method for your applet:

  public class TheApplet extends JApplet { int width, height; public void init() { width = getSize().width; height = getSize().height; setBackground( Color.black ); } public void paint( Graphics g ) { g.setColor( Color.orange ); for ( int i = 0; i < 10; ++i ) { g.drawLine( width / 2, height / 2, i * width / 10, 0 ); } } public static void main(String args[]) { TheApplet applet = new TheApplet(); JFrame frame = new JFrame("Your Test Applet"); frame.getContentPane().add(applet); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(640,480); frame.setLocationRelativeTo(null); frame.setVisible(true); applet.init(); } } 

This should work if I did not miss something - I updated its working code, which I have running on my machine.

+2
source

All Articles