如何重新定位小程序查看器窗口?

8

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

2个回答

7
与其他海报相比,我认为这是一项无意义的练习,并更喜欢他们提出的建议,即制作一个混合应用程序/小程序以使开发更加容易。 另一方面,“我们拥有技术”。在小程序查看器中,小程序的顶级容器通常是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);
        }
    }
}

太好了!我从来不知道这是可能的,事实上,我甚至从未考虑过。谢谢你分享! - Ewald

2

有趣的问题。

我还没有找到可靠的方法来影响AppletViewer,除非在Windows上使用脚本从批处理文件模式启动它,即使如此也不能很好地运行。

另一种替代方法是编写测试代码,使Applet在JFrame中启动,您可以轻松将其居中。

向您的Applet添加一个main方法:

 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();

    }
}

这应该可以正常工作,除非我漏掉了什么 - 我已经更新了在我的机器上运行的代码。


"有趣的问题。" 我不同意,但+1给其他部分。 - Andrew Thompson
@AndrewThompson 我明白你的意思!非常棒的技术答案,我不知道原来可以这样做。 - Ewald

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接