GribBaglayout无法正确显示

时间:2014-08-31 19:15:55

标签: java swing layout-manager gridbaglayout

我试图让我的Label和combobox更加靠近,并将我的textarea放在我的框架的底部。我的组合框和标签紧挨着,但距离错误,我看不到我的文本区域。然后,当我调整框架大小时,一切都显示出来,我的组合框和文本区域是合适的大小,只是间距错误。我认为这是一个重量问题,但是当我调整重量数时,我没有变化。谢谢你的帮助!

以下是代码:

 //add menu items 
     menu1.add(save);
     menu1.add(close);
     menu.add(menu1);
     menu.add(menu2);
     //Creates tabbed items
     tab.addTab("Scan", null, tab1, "Start a scan!");
     tab.addTab("Timed Scan", null, tab2, "Start a timed Scan");

     //add GUI items 
     panel.setLayout(new BorderLayout());
     panel.add(menu, BorderLayout.NORTH);
     panel.add(tab);


      JButton IPscan = new JButton("IP");
     JTextArea response = new JTextArea();
     Dimension textSize = new Dimension(400,100);
     Dimension comboSize = new Dimension(100,25);
     response.setPreferredSize(textSize);

     //Tab1
     GridBagLayout gridBagLayout = new GridBagLayout();
     GridBagConstraints c = new GridBagConstraints();
    // c.weightx = .1;
     c.weighty = .5;
    tab1.setLayout(gridBagLayout);
     response.setLineWrap(true);
     response.setWrapStyleWord(true);
     response.setText("Scan results:");
     c.gridx = 0;
     c.gridy = 4;
     tab1.add(response, c);
     c.anchor = GridBagConstraints.NORTHWEST;
     c.gridx = 0;
     c.gridy = 0;
     tab1.add(choseScan, c);
     scanOp.setPreferredSize(comboSize);
     c.gridx = 1;
     tab1.add(scanOp,c);


     //tab2
     tab2.setLayout(gridBagLayout);
     c.gridx = 1;
     c.gridy = 1;
     tab2.add(scan1, c);



     frame.add(panel);
     frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
     Dimension d = new Dimension(500,500);
     frame.setPreferredSize(d);
     frame.pack();
     //shows everything
     frame.setVisible(true);



     return 5;
 }

1 个答案:

答案 0 :(得分:0)

我无法运行您的代码,但我立即看到一件事可能导致您的初始大小调整不正确。

frame.add(panel);

如果你尝试这样的话:

frame.setLayout(new GridBagLayout());

GridBagConstraints gBC = new GridBagConstraints();
gBC.fill = GridBagConstraints.BOTH;
gBC.weightx = 1.0;
gBC.weighty = 1.0;

frame.add(panel, gBC);

将JTabbedPane添加到JPanel时,您也希望这样做。