2012-03-21 70 views
1

在下面的代碼中,當我將JTextArea添加到主面板時,它不會顯示出來。當我添加controlPanel時,它顯示在中心,而不是邊緣。我是GridBagLayout的新手,所以我假設我缺少一些簡單的東西。GridBagLayout不顯示JTextArea,並在中心顯示面板

import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JSpinner; 
import javax.swing.JTextArea; 

public class Main { 

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

    public Main() { 
     JFrame frame = new JFrame(); 

     JPanel mainPanel = new JPanel(); 
     JPanel controlPanel = new JPanel(); 

     mainPanel.setLayout(new GridBagLayout()); 
     GridBagConstraints c = new GridBagConstraints(); 

     controlPanel.add(new JButton("Play")); 
     controlPanel.add(new JButton("Pause")); 
     controlPanel.add(new JSpinner()); 
     JTextArea textArea = new JTextArea(); 

     c.gridx = 0; 
     c.gridy = 0; 
     c.gridheight = 3; 
     c.gridwidth = 3; 
     mainPanel.add(textArea, c); 
     // mainPanel.add(controlPanel, c); 
     frame.add(mainPanel); 

     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(700, 700); 
     frame.setLocation(250, 100); 
     frame.setVisible(true); 
    } 
} 

編輯:這是限制你的建議後怎麼看。 textArea仍然不顯示。

 c.gridx = 0; 
     c.gridy = 0; 
//  c.gridheight = 3; 
//  c.gridwidth = 3; 
     c.weightx = 1.0; 
     c.weighty = 1.0; 
     c.anchor = GridBagConstraints.NORTHWEST; 
     mainPanel.add(textArea, c); 
     // mainPanel.add(controlPanel, c); 
     frame.add(mainPanel); 
+0

你爲什麼期待它出現在邊緣? – 2012-03-21 19:08:55

+0

@ TomHawtin-tackline是不是gridx = 0和gridy = 0意味着什麼? – gsingh2011 2012-03-21 19:11:16

+1

不,他們只是任意網格數字。對於GB,使用一些weightx在右側添加一個間隔元件。 – 2012-03-21 19:14:28

回答

2

不要忘記權錨:

c.weightx = 1.0; 
    c.weighty = 1.0; 
    c.anchor = GridBagConstraints.NORTHWEST; 

編輯:
添加行和列值的JTextArea中的 例子:

controlPanel.add(new JButton("Play")); 
    controlPanel.add(new JButton("Pause")); 
    controlPanel.add(new JSpinner()); 

    JTextArea textArea = new JTextArea(20, 40); 

    c.gridx = 0; 
    c.gridy = 0; 
    c.gridheight = 3; 
    c.gridwidth = 3; 
    c.weightx = 1.0; 
    c.weighty = 1.0; 
    c.anchor = GridBagConstraints.NORTHWEST; 
    mainPanel.add(new JScrollPane(textArea), c); 
+0

它將controlPanel放置在正確的位置,但textArea不顯示。任何想法爲什麼? – gsingh2011 2012-03-21 23:47:14

+0

@gsingh:它可能有一個非常小的尺寸。考慮使用接受行和列並傳入合理數字的文本區域構造函數,例如20行和40列,並且還應該將JTextArea放入JScrollPane中。 – 2012-03-22 02:46:39

+0

@ gsingh2011:參見編輯例如我的意思。 – 2012-03-22 02:48:11

1

我完全嚴肅的答案是不使用GridBagLayout。 GUI窗體構建器保留GridBagLayout。

如果您想手動構建GUI(我建議手動構建它們並避免表單構建器,順便說一句),那麼通常使用BoxLayouts嵌套面板的BorderLayout實際上是您最好的選擇。