我在使用GridBagLayout重新定位JTab中的按钮,字段和标签时遇到问题。我不确定如何在我的JTab中重新定位。按钮和这样的节目,但它们都显示在一行而不是采取我设置的限制。
我想将第一张图片中的布局实现到JTabbedPane中的第二张图片中,正如您所看到的,当我使用JTabs时,所有内容都保持在一行中。
Before implementing JTabbedPane
After implementing JTabbedPane
我附上了以下代码的一部分:
private void programProperties() {
reStockButton.addActionListener(this);
sellButton.addActionListener(this);
setPriceButton.addActionListener(this);
getNameButton.addActionListener(this);
getStockLevelButton.addActionListener(this);
getPriceButton.addActionListener(this);
panel.setLayout(new GridBagLayout());
panel.add(menuTabs, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
menuTabs.add("Description", productDescription);
menuTabs.add("Sale", productSale);
menuTabs.add("Restock", productRestock);
gbc.gridx = 0;
gbc.gridy = 0;
productRestock.add(reStockLabel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
productSale.add(sellLabel, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
productDescription.add(setPriceLabel, gbc);
gbc.gridx = 3;
gbc.gridy = 0;
productDescription.add(getNameLabel, gbc);
gbc.gridx = 4;
gbc.gridy = 0;
productDescription.add(getStockLevelLabel, gbc);
gbc.gridx = 5;
gbc.gridy = 0;
productDescription.add(getPriceLabel, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
productDescription.add(reStockField, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
productSale.add(sellField, gbc);
gbc.gridx = 2;
gbc.gridy = 2;
productRestock.add(setPriceField, gbc);
gbc.gridx = 3;
gbc.gridy = 2;
productDescription.add(getNameField, gbc);
gbc.gridx = 4;
gbc.gridy = 2;
productDescription.add(getStockLevelField, gbc);
gbc.gridx = 5;
gbc.gridy = 2;
productDescription.add(getPriceField, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
productRestock.add(reStockButton, gbc);
gbc.gridx = 1;
gbc.gridy = 3;
productSale.add(sellButton, gbc);
gbc.gridx = 2;
gbc.gridy = 3;
productDescription.add(setPriceButton, gbc);
gbc.gridx = 3;
gbc.gridy = 3;
productDescription.add(getNameButton, gbc);
gbc.gridx = 4;
gbc.gridy = 3;
productDescription.add(getStockLevelButton, gbc);
gbc.gridx = 5;
gbc.gridy = 3;
productDescription.add(getPriceButton, gbc);
menuBar();
frame.setTitle("Program");
frame.setSize(750,300);
frame.setLocation(500,300);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
答案 0 :(得分:0)
首先,组件只能有一个父组件。您要添加两次标签,这样只会将标签添加到第二个容器中。
其次,您没有在所有添加中包含gbc参数,如下所示
td.when
我相信你的问题就在你打电话的地方
gbc.gridx = 5;
gbc.gridy = 0;
panel.add(getPriceLabel, gbc);
productDescription.add(getPriceLabel);
您应该改为呼叫 panel.setLayout(new GridBagLayout());
。