[英]Jpanels with Gridbaglayout inside a JPanel with GridbagLayout problems
[英]GridBagLayout inside a JPanel and JPanel inside GridBagLayout
我有兩個Java類:
GridBagLayout
,以便可以將class2的實例添加到列表中。 我的代碼如下:
1類
class2 one = new class2();
class2 two = new class2();
this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(6,2,6,40);
gbc.gridx = 0;
this.add(new JLabel("Name"), gbc);
gbc.gridx = 1;
this.add(new JLabel("Surname"), gbc);
gbc.gridx = 2;
this.add(new JLabel("Age"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
this.add(one, gbc);
gbc.gridy = 2;
this.add(two, gbc);
Class2擴展了JPanel
this.setLayout(new GridBagLayout());
GridBagConstraints gridBagCons = new GridBagConstraints();
gridBagCons.insets = new Insets(6,2,6,4);
gridBagCons.gridx = 0;
this.add(new JTextField(10), gridBagCons);
gridBagCons.gridx = 1;
this.add(new JTextField(10), gridBagCons);
gridBagCons.gridx = 2;
this.add(new JTextField(10), gridBagCons);
因此,它不起作用,它顯示了標題:我想要的名稱,姓氏和年齡,以及在class1的GridBagLayout的第一列中從class2導入的其他兩個面板。 我想將標題與從class2導入的文本字段對齊。
拜托,你能看看我嗎。
您需要在GridBagConstraints
上設置gridwidth
。 您的示例創建了一個3x3的網格。 標題在第一行。 在第二行中,第一個位置包含整個Class2
面板,而列2和3沒有任何內容。 第三行也一樣。
放
gbc.gridWidth = 3;
在添加Class2
面板之前。
要對齊文本字段,請輸入
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
對於“標題”的每個標簽和類別2的每個文本字段。手動設置插圖將無法正確調整大小。
您可以手動調整插圖
gbc.insets = new Insets(6,2,6,90);
gbc.gridx = 0;
this.add(new JLabel("Name"), gbc);
gbc.insets = new Insets(6,0,6,-20);
gbc.gridx = 1;
this.add(new JLabel("Surname"), gbc);
gbc.insets = new Insets(6,0,6,0);
gbc.gridx = 2;
this.add(new JLabel("Age"), gbc);
gbc.gridx = 0;
gbc.gridwidth = 3;
gbc.gridy = 1;
this.add(one, gbc);
gbc.gridy = 2;
this.add(two, gbc);
盡管您可能最好不要使用第二個類,而是根據實現以其他方式添加文本字段。
編輯:這是一種使用GridLayout
動態添加字段的方法
public class AddingFields {
static GridLayout gl = new GridLayout(2, 3, 20, 10);
static JFrame frame = new JFrame();
public static void main(String[] args) {
new AddingFields();
createAdderFrame();
}
AddingFields() {
frame.setLayout(gl);
frame.add(new JLabel("Name"));
frame.add(new JLabel("Surname"));
frame.add(new JLabel("Age"));
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static void createAdderFrame() {
JFrame adder = new JFrame();
JButton addButton = new JButton("Add row");
adder.add(addButton);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
gl.setRows(gl.getRows() + 1);
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.add(new JTextField(10));
frame.pack();
}
});
adder.pack();
adder.setVisible(true);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.