2011-11-19 181 views
1

我想沿着側頂部以下鋪陳......的Java Swing佈局

  • Jbutton將海誓山盟。
  • JTextArea應該是下的的按鈕。
  • JTextArea還應該有一個滾動條
    ...代碼如下。

    JPanel jp = new JPanel(); 
    One = new JButton("One"); 
    Two = new JButton("Two");  
    TestOutput = new JTextArea(); 
    
    jp.add(One); 
    jp.add(Two); 
    jp.add(TestOutput); 
    
+1

請學習Java命名約定並嚴格遵守 – kleopatra

回答

2

關鍵字是分層 - 在JPanel上有JPanel。

+0

這對我有效。謝謝彼得! –

+0

這個例子有一些方面非常好,而其他方面則不太好。例如。 +1'new JTextArea(4,35);',-1'setMinimumSize' /'setSize'。 (第一個使第二個冗餘。)整體+1。請考慮以後再編譯一個可編譯/可運行的示例 - 它通常只需要一些額外的LOC。 –

2

使用GridBagLayout

如需更多幫助,請參閱本:How to Use GridBagLayout

現在注意,JTextarea有一個滾動條都無關佈局。 How to Use Scroll Panes

+0

我儘快轉而反對這個答案,因爲我看到'GridBagLayout'。雖然GBL功能強大,但編寫和使用和調試的難度要比嵌套佈局要長(對於這種簡單的GUI佈局)。 OTOH包括J7文檔的鏈接和2個指向教程的鏈接,其中一個關於我們似乎都同意的問題(滾動窗格)。 +1 –

3

使用嵌套佈局:

在這方面更多的幫助,請參閱本要爲BorderLayout一個JPanel

  • 的按鈕添加JPanelFlowLayoutNORTH
  • JScrollPaneJTextAreaCENTER
1

您可以使用的GridBagLayout的建議,或者嵌套多個佈局管理器如:

JFrame frame = new JFrame(); 
frame.setLayout(new BorderLayout()); 

JPanel buttonPanel = new JPanel(); 
JButton oneButton = new JButton("One"); 
JButton twoButton = new JButton("Two"); 
buttonPanel.add(oneButton); 
buttonPanel.add(twoButton); 

JTextArea output = new JTextArea(); 
JScrollPane scrollPane = new JScrollPane(output); 

frame.add(buttonPanel, BorderLayout.NORTH); 
frame.add(scrollPane); 
frame.pack(); 
frame.setVisible(true); 
2

FlowLayoutJPanelJButton實例是一條路可走。您也可以使用JToolBar作爲按鈕。

Buttons and TextArea LayoutButtons and TextArea Layout w. toolbar on RHS

import java.awt.*; 
import javax.swing.*; 

class ButtonsAndTextAreaLayout { 

    ButtonsAndTextAreaLayout() { 
     JPanel gui = new JPanel(new BorderLayout(5,5)); 

     // use a toolbar for the buttons 
     JToolBar tools = new JToolBar(); 
     // use firstWordLowerCase for attribute/method names. 
     JButton one = new JButton("One"); 
     JButton two = new JButton("Two"); 

     tools.add(one); 
     tools.add(two); 

     // provide hints as to how large the text area should be 
     JTextArea testOutput = new JTextArea(5,20); 

     gui.add(tools, BorderLayout.NORTH); 
     gui.add(new JScrollPane(testOutput), BorderLayout.CENTER); 

     JOptionPane.showMessageDialog(null, gui); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       new ButtonsAndTextAreaLayout(); 
      } 
     }); 
    } 
}