2012-10-23 49 views
6

我是Java编程的新手,我试图创建一个包含两个按钮和一个文本区域的窗口,如下图所示。 我遇到的问题是定位组件。我尝试使用GridLayout并将窗口分成9行和16个单元格,但后来发现我无法使组件占用多个单元格。我知道我应该使用GridBagLayout但我不知道如何。帮助将不胜感激。 :)如何使用GridBagLayout定位组件?

+0

所有JComponents都可以使用容器调整大小,或不调整ei – mKorbel

回答

7

您有多种选择。而不是试图布局整个组件于一体,尝试使用复合布局,其中由你布局单独的窗格和注重每一节的个性化需求的UI的部分...

enter image description here

public class TestLayout11 { 

    public static void main(String[] args) { 
     new TestLayout11(); 
    } 

    public TestLayout11() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException ex) { 
       } catch (InstantiationException ex) { 
       } catch (IllegalAccessException ex) { 
       } catch (UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame("Test"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new ExamplePane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    protected class ExamplePane extends JPanel { 

     public ExamplePane() { 
      setLayout(new GridBagLayout()); 

      JPanel buttonPane = new JPanel(new GridBagLayout()); 

      JButton btnOkay = new JButton("Ok"); 
      JButton btnCancel = new JButton("Cancel"); 

      JTextArea textArea = new JTextArea(5, 20); 

      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      gbc.fill = GridBagConstraints.HORIZONTAL; 
      gbc.anchor = GridBagConstraints.CENTER; 
      buttonPane.add(btnOkay, gbc); 
      gbc.gridy++; 
      gbc.insets = new Insets(50, 0, 0, 0); 
      buttonPane.add(btnCancel, gbc); 

      gbc.gridx = 0; 
      gbc.gridy = 0; 
      gbc.insets = new Insets(100, 100, 100, 100); 
      add(buttonPane, gbc); 

      gbc.insets = new Insets(150, 100, 150, 100); 
      gbc.gridx++; 
      gbc.gridy = 0; 
      gbc.fill = GridBagConstraints.BOTH; 
      add(new JScrollPane(textArea), gbc);     
     }    
    }   
}