简体   繁体   中英

Keep the jframe open on a dual monitor configuration in Java

I have a dual monitor configuration and I managed to open my Jframe on the desired screen.

But the problem is, every time I click on my main screen the other window minimizes, but I needed to always be on top.

PS: I checked the always on top check box

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();

that's how I'm using the other screen.

As long as I use setFullScreenWindow I do get the same issue. Replacing the frames by dialogs solves the issue but I guess you really want to have a frame, not a dialog.

So the solution is to manually maximize the frame instead of using setFullScreenWindow:

import java.awt.*;
import javax.swing.*;

public class MultiMonitorFrame extends JFrame {

    public static void showFrameOnScreen(Window frame, int screen) {
        GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] graphicsDevices = graphicsEnvironment.getScreenDevices();
        GraphicsDevice graphicsDevice = ( screen > -1 && screen < graphicsDevices.length ) ? graphicsDevices[screen] : graphicsDevices.length > 0 ? graphicsDevices[0] : null;
        if (graphicsDevice == null)
        {
            throw new RuntimeException( "There are no screens !" );
        }
        Rectangle bounds = graphicsDevice.getDefaultConfiguration().getBounds();
        frame.setSize(bounds.width, bounds.height);
        frame.setLocation(bounds.x, bounds.y);
    }

    public static void main(String[] args) {
        JFrame frame1 = new JFrame("First frame");
        frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame1.setVisible(true);
        frame1.setAlwaysOnTop(true);
        JFrame frame2 = new JFrame("Second frame");
        frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame2.setVisible(true);
        frame2.setAlwaysOnTop(true);
        showFrameOnScreen(frame1, 1);
        showFrameOnScreen(frame2, 2);
    }
}

This shows the two frames each on one monitor and the frames do not get minimized when using ALT-Tab or clicking on the desktop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM