所以这是你的代码用GridBagLayout改变BorderLayout. GridBagLayout的核心思想是,您将拥有一个包含多个行和列(不同大小)的网格,您可以在每个单元格中放置组件.它的巧妙之处在于它非常强大:当您将组件放置在单元格中时,您可以自定义以下内容:
>它可以跨越多少个单元格(垂直,水平或两者)(网格宽度/网格高度)
>在细胞中放置的位置:中心,左上,右下……(锚)
>每行/每列的重量,这是在调整窗口大小/分配时它们按比例占用的空间. (重量,重量)
>他们是否必须占用所需的最大或最小空间. (填)
除其他事项外.最后一点是你的问题,BorderLayout迫使你的面板尽可能地扩展.在我的代码中,我使用fill = NONE并将其设置为anchor = LAST_LINE_START,因此它保持在左下角并且不会展开.
您可以使用这些参数,所有信息都是in the tutorial.
所有这一切的关键是要知道你的网格是怎样的.在这个例子中,它非常简单,仅为1×1.但是看一下教程:那些带有红色网格的图像,这就是你必须拥有的东西.除此之外,了解所有变量,唯一棘手的问题是权重如何运作.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main {
//Settings Panel variables
JLabel settingsTitle = new JLabel("Settings");
public Main()
{
JPanel mainCard = new JPanel(new GridBagLayout());
JPanel settingsPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
settingsTitle.setFont(new Font("TimesRoman", Font.PLAIN, 35));
settingsPanel.add(settingsTitle);
final CardLayout layout = new CardLayout();
final JPanel cards = new JPanel(layout);
cards.add(mainCard, "2");
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weightx = 1.0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.LAST_LINE_START;
c.fill = GridBagConstraints.NONE; //uneeded line because it's the default value, but it has to be NONE
mainCard.add(settingsPanel, c);
// settingsPanel.setPreferredSize(new Dimension(300, 425)); //the components inside settingsPanel will set its side
settingsPanel.setBorder(BorderFactory.createLineBorder(Color.black));
layout.show(cards, "1");
JFrame window = new JFrame("Test");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(cards);
window.setSize(1280, 720); ///replace with window.pack()
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Main();
}
});
}
}