java jframe最da化代码,在Java中最大化JFrame

在Windows 10上使用Java 8时,通过代码设置JFrame最大化可能会导致窗口底部重叠并偏离左侧。问题在于`setLocationRelativeTo(null)`方法与`setExtendedState(JFrame.MAXIMIZED_BOTH)`的顺序。正确做法是移除`setLocationRelativeTo(null)`或在设置最大化状态之前调用,以避免窗口位置异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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):

sKTGd.png

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

}

}

解决方案

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值