我正试图找出一种方法,使用gridbaglayout将包含组合框的面板放在我的JFrame中。目前它出现在另一个相同类型的面板旁边。
这是它的样子:
以下是特定区域的代码
JPanel saleOfferPanel = new JPanel();
JLabel dateOfSale = new JLabel("Select Date of Sale:");
saleOfferPanel.add(dateOfSale);
JLabel saleDay = new JLabel("Day:");
saleOfferPanel.add(saleDay);
JComboBox<Integer> dayOfSale = new JComboBox<>();
saleOfferPanel.add(dayOfSale);
JLabel saleMonth = new JLabel("Month:");
saleOfferPanel.add(saleMonth);
JComboBox<Integer> monthOfSale = new JComboBox<>();
saleOfferPanel.add(monthOfSale);
JLabel saleYear = new JLabel("Year:");
saleOfferPanel.add(saleYear);
JComboBox<Integer> yearOfSale = new JComboBox<>();
saleOfferPanel.add(yearOfSale);
JPanel endSalePanel = new JPanel();
JLabel endOfSale = new JLabel("Select End Date of Sale:");
saleOfferPanel.add(endOfSale);
JLabel endDay = new JLabel("Day:");
saleOfferPanel.add(endDay);
JComboBox<Integer> endDayOfSale = new JComboBox<>();
saleOfferPanel.add(endDayOfSale);
JLabel endMonth = new JLabel("Month:");
saleOfferPanel.add(endMonth);
JComboBox<Integer> endMonthOfSale = new JComboBox<>();
saleOfferPanel.add(endMonthOfSale);
JLabel endYear = new JLabel("Year:");
saleOfferPanel.add(endYear);
JComboBox<Integer> endYearOfSale = new JComboBox<>();
saleOfferPanel.add(endYearOfSale);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 0.5;
gbc.weighty = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
//other panels...
//panels in question
gbc.gridx = 0;
gbc.gridy = 9;
gbc.gridheight = 1;
add(saleOfferPanel, gbc);
gbc.gridx = 0;
gbc.gridy = 10;
gbc.gridheight = 1;
add(endSalePanel, gbc);
希望有人可以提供帮助。
由于
答案 0 :(得分:0)
我已经改变了你的代码并成功改变了它的位置。这是代码片段。
`// setLayout(new GridBagLayout());
GridBagLayout gb = new GridBagLayout();
this.setLayout(gb);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.BOTH;
//other panels...
//panels in question
gbc.gridwidth = GridBagConstraints.REMAINDER; //this will tell GridBagLayout component below should be last one on this line.
gb.setConstraints(saleOfferPanel, gbc);
this.add(saleOfferPanel);
gb.setConstraints(endSalePanel, gbc);
this.add(endSalePanel);
this.pack();
this.setSize(500, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);`
答案 1 :(得分:0)
仔细查看创建并填充endSalePanel
的代码:
JPanel endSalePanel = new JPanel();
JLabel endOfSale = new JLabel("Select End Date of Sale:");
//[KA] Here's where it all starts to go wrong!!! You wanted to add
// endOfSale to endSalePanel, but...
saleOfferPanel.add(endOfSale);
JLabel endDay = new JLabel("Day:");
saleOfferPanel.add(endDay);
再次剪切并粘贴!