编辑:我制作了一个示例应用程序,演示如何使用重用约束的 GridBadLayout:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test1 window = new Test1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JButton btnTest = new JButton("Test1");
GridBagConstraints gbc_btnTest = new GridBagConstraints();
gbc_btnTest.insets = new Insets(0, 0, 0, 5);
gbc_btnTest.gridx = 0;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest, gbc_btnTest);
JButton btnTest_1 = new JButton("Test2");
gbc_btnTest.gridx = 1;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest_1, gbc_btnTest);
}
}