java setsize没有作用,Java JFrame .setSize(x,y)不起作用?

这篇博客介绍了解决Java Swing中JFrame窗口大小设置问题的方法。通过创建一个继承自JPanel的自定义组件,并重写getPreferredSize方法返回所需尺寸,然后将其设置为frame的内容面板,最后调用frame.pack()来确保窗口根据内容调整大小。

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

When I execute this bit of code, a tiny window pops up that, and the inside of it is about 116x63, and the entire size including the border of ~140x100. How do I set the inside to be what I need it to?

public static void graphics() {

JFrame frame = new JFrame();

String title = "test window";

frame.setTitle(title);

frame.setSize(gridRow, gridCol); //101 x 101

frame.setResizable(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

解决方案

Create a custom component, extending from JPanel, override its getPreferredSize method to return the size of the window you would like.

Either add this to your frame or set it as the frame's content pane.

Call pack on the frame

Updated with example

2KzJ0.png

On my PC, the Frame size = java.awt.Dimension[width=216,height=238]

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.EventQueue;

import java.awt.FontMetrics;

import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.UIManager;

import javax.swing.UnsupportedLookAndFeelException;

public class TestFrameSize01 {

public static void main(String[] args) {

new TestFrameSize01();

}

public TestFrameSize01() {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

try {

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {

}

JFrame frame = new JFrame("Testing");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new BorderLayout());

frame.add(new TestPane());

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

System.out.println("Frame size = " + frame.getSize());

}

});

}

public class TestPane extends JPanel {

public TestPane() {

}

@Override

public Dimension getPreferredSize() {

return new Dimension(200, 200);

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2d = (Graphics2D) g.create();

String text = getWidth() + "x" + getHeight();

FontMetrics fm = g2d.getFontMetrics();

int x = (getWidth() - fm.stringWidth(text)) / 2;

int y = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();

g2d.drawString(text, x, y);

g2d.dispose();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值