更改 gridx 和 gridy 不会更改标签的实际位置,而是更改标签显示的顺序/格式。如果您在 gridx 4 中有某些内容,但在 gridx 1,2 或 3 中没有任何内容,则该对象将是第一列。此外,在每列中放置一个新面板会很奇怪,因为您可以将内容放在 gridBagLayout 的不同行中。下面是一个带有三个不同标签列的 flowLayout 中的 gridBagLayout 的简短示例:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
public class nest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nest frame = new nest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public nest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 1, 0, 0));
JPanel panel = new JPanel();
contentPane.add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{0, 0, 27, 0};
gbl_panel_1.rowHeights = new int[]{0, 16, 0};
gbl_panel_1.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblNewLabel_1 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 0;
panel_1.add(lblNewLabel_1, gbc_lblNewLabel_1);
JLabel lblNewLabel = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel_1.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_2.gridx = 2;
gbc_lblNewLabel_2.gridy = 0;
panel_1.add(lblNewLabel_2, gbc_lblNewLabel_2);
JLabel lblLabel = new JLabel("New label");
GridBagConstraints gbc_lblLabel = new GridBagConstraints();
gbc_lblLabel.gridx = 2;
gbc_lblLabel.gridy = 1;
panel_1.add(lblLabel, gbc_lblLabel);
}
}
我用 Google WindowBuilder 创建了这个。请注意,您不一定需要设置 columnWidths、rowHeights、columnWeights 或 rowWeights(有时当您有动态内容时最好不要设置)。希望这会有所帮助。