Maximizing JFrame in Java

怎甘沉沦 提交于 2019-12-25 04:50:44

问题


There have been several questions related to this, for example here and here, that both say the way to maximize a JFrame is to use the following code:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH); //Some answers have these lines
frame.setVisible(true);                        //reversed

However, for me, not sure if this is a windows 10 bug/java 8 bug or not, when I use this code the result is this (no matter which way round the two lines of code above are):

As you can see in the image, the window is the correct size, however, it slightly overlays the bottom, and it is slightly offset from the left. Is there a way to fix this problem, or actually maximise the program by hitting the maximise button on the JFrame with code?

Edit
Here is a MCVE that demonstrates the problem:

import java.awt.GridLayout;
import javax.swing.JFrame;

public class CDBurner extends JFrame {
    private static final long serialVersionUID = -6027473114929970648L;

    private CDBurner() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(1, 1));
        setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);
        setVisible(true);
        setLocationRelativeTo(null);
        requestFocus();
    }

    public static void main(String[] args) {
        new CDBurner();
    }
}

回答1:


The line

setLocationRelativeTo(null);

sets the position of the frame. If it comes after

setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);

it changes the location of the frame after it maximizes, causing the gap you observed. You should remove that line since maximizing the frame sets its position anyway (though you can just put it before setting the extended state, in which case it does nothing).



来源:https://stackoverflow.com/questions/40436467/maximizing-jframe-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!