【问题标题】:How to use JFrame to open another JFrame window on the other monitor?如何使用 JFrame 在另一台显示器上打开另一个 JFrame 窗口?
【发布时间】:2013-01-15 21:21:20
【问题描述】:

我正在编写一个旨在在两个监视器系统上工作的程序。我必须分开 JFrame 对象,并让它默认,第一个框架实例打开。然后,用户必须将该帧拖到特定的监视器上,或者将其留在原处。当他们单击该框架上的按钮时,我希望程序在对面的监视器上打开第二个框架。

那么,我如何确定一个框架对象在哪个监视器上,然后告诉另一个框架对象在对面的监视器上打开?

【问题讨论】:

标签: java swing jframe awt multiple-monitors


【解决方案1】:

查看GraphicsEnvironment,您可以轻松找出每个屏幕的边界和位置。之后,就只是玩帧位置的问题了。

在此处查看小演示示例代码:

import java.awt.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class TestMultipleScreens {

    private int count = 1;

    protected void initUI() {
        Point p = null;
        for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
            p = gd.getDefaultConfiguration().getBounds().getLocation();
            break;
        }
        createFrameAtLocation(p);
    }

    private void createFrameAtLocation(Point p) {
        final JFrame frame = new JFrame();
        frame.setTitle("Frame-" + count++);
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        final JButton button = new JButton("Click me to open new frame on another screen (if you have two screens!)");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                GraphicsDevice device = button.getGraphicsConfiguration().getDevice();
                Point p = null;
                for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
                    if (!device.equals(gd)) {
                        p = gd.getDefaultConfiguration().getBounds().getLocation();
                        break;
                    }
                }
                createFrameAtLocation(p);
            }
        });
        frame.add(button);
        frame.setLocation(p);
        frame.pack(); // Sets the size of the unmaximized window
        frame.setExtendedState(Frame.MAXIMIZED_BOTH); // switch to maximized window
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestMultipleScreens().initUI();
            }
        });
    }

}

不过,请考虑仔细阅读The Use of Multiple JFrames, Good/Bad Practice?,因为它们会带来非常有趣的考虑。

【讨论】:

  • 谢谢。对于我正在编写的应用程序,我需要有多个框架,因为它是为“演示”而设计的,所以我真的无能为力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多