2012-10-23 78 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);     
     }    
    }   
}