如何使 JPanel 的大小适用于 JFrame?

huangapple go评论66阅读模式
英文:

How to make JPanel size apply to JFrame?

问题

我遇到了一个关于JPanel的大小不会增加JFrame大小的问题。

以下是我的代码:

package pong;

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		
		JPanel p = new JPanel();
		p.setPreferredSize(new Dimension(500, 500));

		frame.add(p);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setVisible(true);
		
		frame.setLocationRelativeTo(null);
	}
}

尽管面板的首选大小为500 x 500像素,但窗口显示的宽度和高度都很小。

英文:

I'm having an issue with the size of the JPanel not increasing a trhe size of a JFrame.

Here is my code:

package pong;

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

	public static void main(String[] args) {
		JFrame frame = new JFrame();
		
		JPanel p = new JPanel();
		p.setPreferredSize(new Dimension(500, 500));

		frame.add(p);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setResizable(false);
		frame.setVisible(true);
		
		frame.setLocationRelativeTo(null);
	}
}

The frame is displayed with little width or height at all, even though the panel's preferred size is 500 by 500 px.

答案1

得分: 2

以下是翻译好的部分:

JFrame显示的宽度或高度都很小,

代码应为:

frame.pack(); // 添加
frame.setVisible(true);

pack() 方法将调用框架使用的布局管理器,并且所有 Swing 组件都将以其首选大小显示。

此外,作为一般规则,通常不需要手动设置面板的首选大小,因为您将向面板添加组件,因此首选大小应基于您添加到面板的组件。

阅读 Swing 教程中的使用布局管理器一节,了解更多信息和示例。

英文:

> The JFrame is displayed with little width or height at all,

The code should be:

frame.pack(); // added
frame.setVisible(true);

The pack() method will invoke the layout manager used by the frame and all the Swing components will be displayed at their preferred size.

Also, as a general rule there should be no need to set the preferred size of the panel manually since you will be adding components to the panel and therefore the preferred size should be based on the components you add to the panel.

Read the section from the Swing tutorial on Using Layout Managers for more information and examples.

huangapple
  • 本文由 发表于 2020年8月3日 01:59:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63219384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定