有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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


共 (2) 个答案

  1. # 1 楼答案

    与另一张海报相比,我认为这是一个毫无意义的练习,我更喜欢他们的建议,即制作一个混合应用程序/applet,以简化开发

    OTOH-“我们有技术”。小程序查看器中小程序的顶级容器通常是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);
            }
        }
    }
    
  2. # 2 楼答案

    有趣的问题

    我还没有找到一种可靠的方法来影响AppletViewer,如果不在Windows上使用脚本从批处理文件模式启动它,即使这样也不太管用

    另一种方法是编写测试代码,使小程序在JFrame中启动,您可以轻松地将其居中

    将主方法添加到小程序:

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

    这应该是可行的,除非我遗漏了什么——我更新了我在机器上运行的it工作代码