我创建了一个名为 homeWindowFrame 的 JFrame 并将其大小设置为 (600, 500),然后向该 JFrame 添加了一个名为 mainContainerPanel 的 JPanel。我为 JPanel 设置了新大小,但它不起作用。 JPanel 大小保持与 JFrame 相同,而不是更新。如何在 JFrame 中设置 JPanel 的大小。提前致谢。这是我的代码:
/** * 主窗口结构 */
JFrame homeWindowFrame = new JFrame("Home - Crime File Management System");
if (isInvalidLogin) {
homeWindowFrame.setSize(600, 500);
} else {
homeWindowFrame.setSize(600, 400);
}
homeWindowFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
homeWindowFrame.setLocation((screenSize.width / 2) - (homeWindowFrame.getWidth() / 2), (screenSize.height / 2) - (homeWindowFrame.getHeight() / 2));
/**
* Main panel construction
*/
JPanel mainContainerPanel;
if (isInvalidLogin) {
mainContainerPanel = new JPanel(new GridLayout(4, 2));
} else {
mainContainerPanel = new JPanel(new GridLayout(3, 2));
}
homeWindowFrame.add(mainContainerPanel);
最佳答案
您的代码似乎忽略了 Java Swing 布局管理器的工作方式。当您将 JPanel 添加到 JFrame 时,默认布局是 BorderLayout,这将使面板在框架中居中,并调整其大小以填充框架。如果您希望拥有不同大小的面板,并且需要以某种方式设置其首选大小,并且容纳 JPanel 的容器将需要使用不同的布局管理器。例如,如果您需要的话,以“默认”方式使用的 GridBagLayout(添加一个组件,无 GridBagConstraints)将使 JPanel 居中。如果这些建议没有帮助,那么您应该创建一个自己的后验 MCVE (请阅读链接)。
例如,我的 MCVE:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import javax.swing.*;
@SuppressWarnings("serial")
public class DiffSizedPanel extends JPanel {
private static final int PANEL_W = 400;
private static final int PANEL_H = 300;
private static final int FRAME_W = 600;
private static final int FRAME_H = 500;
private static final Color BG_COLOR = Color.PINK;
public DiffSizedPanel() {
setBackground(BG_COLOR);
// set the JPanel the preferred size desired
setPreferredSize(new Dimension(PANEL_W, PANEL_H));
setBorder(BorderFactory.createTitledBorder("This is the JPanel"));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Different Sized Panel");
// set the JFrame the preferred size desired
frame.setPreferredSize(new Dimension(FRAME_W, FRAME_H));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// change the content pane's layout from default BorderLayout to GridBagLayout
frame.getContentPane().setLayout(new GridBagLayout());
frame.getContentPane().add(new DiffSizedPanel()); // add the JPanel
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
关于java - 如何防止 JPanel 继承其容器 JFrame 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46025071/