我正在编写一个专门用于两个监视器系统的程序。我必须将JFrame
对象分开,并将其设置为默认值,将打开第一个框架实例。然后用户必须将该框架拖到特定的监视器上,或保留原位。当他们点击该框架上的按钮时,我希望程序在相反的监视器上打开第二帧。如何使用JFrame在另一台显示器上打开另一个JFrame窗口?
那么,我怎样才能找出一个框架对象在哪个监视器上,然后告诉另一个框架对象在另一个框架对象上打开?
我正在编写一个专门用于两个监视器系统的程序。我必须将JFrame
对象分开,并将其设置为默认值,将打开第一个框架实例。然后用户必须将该框架拖到特定的监视器上,或保留原位。当他们点击该框架上的按钮时,我希望程序在相反的监视器上打开第二帧。如何使用JFrame在另一台显示器上打开另一个JFrame窗口?
那么,我怎样才能找出一个框架对象在哪个监视器上,然后告诉另一个框架对象在另一个框架对象上打开?
查找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?,因为他们带来了非常有趣的考虑。
谢谢。对于我正在编写的应用程序,我需要有多个框架,因为它是为“演示文稿”而设计的,因此我无法做其他任何事情。 –
1)什么是应用程序。特别?请参阅[使用多个JFrames,好/坏实践?](http://stackoverflow.com/a/9554657/418556)2)查看['GraphicsEnvironment'](http://docs.oracle.com/ javase/7/docs/api/java/awt/GraphicsEnvironment.html)&['GraphicsDevice'](http://docs.oracle.com/javase/7/docs/api/java/awt/GraphicsDevice.html)对象它揭示。根据@mKorbel提示进行了更正。 +1 –