2016-01-31 62 views
0

爲什麼Jtextarea沒有出現在這段代碼中? 我試着在jpanel中使用gridbaglayout添加一個Jtextarea。 框架可以正常打開,但沒有Jtextarea。 我無法識別問題。請有人幫助我。爲什麼JTextArea沒有出現在這段代碼中?

import javax.swing.*; 
    import java.awt.*; 
    public class ServerTest{ 
    //object declaration 
    JFrame f; 
    JPanel p; 
    JTextArea ta; 
    JTextField tf; 
    JButton b1,b2; 
    GridBagConstraints gbc; 
    //constructor 
    public ServerTest(){ 
     //instantiation 
     f=new JFrame("Server"); 
     p=new JPanel(); 
     p.setBackground(Color.green); 
     ta=new JTextArea("Hello"); 
     tf=new JTextField(); 
     b1=new JButton("EMO"); 
     b2=new JButton("VOICE"); 
     gbc=new GridBagConstraints(); 
     //end of instantiation 

     //frame task 
     f.setLayout(new FlowLayout()); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     p.setLayout(new GridBagLayout()); 

     gbc.gridx=0; 
     gbc.gridy=0; 
     gbc.gridwidth=3; 
     gbc.gridheight=5; 
     p.add(ta,gbc); 
     f.add(p); 
     f.pack(); 
     f.setVisible(true); 
     //end of frame task 

    } 

    //Main method 
    public static void main(String []args){ 
     ServerTest st = new ServerTest(); 
    } 
} 
+0

_but沒有的JTextArea上it._但在這裏我沒有找不到像這樣的問題。 – Satya

+0

與@Satya發現的一樣,代碼似乎對我也很好。 – DevilsHnd

+0

是的,你們都是對的..這是一個愚蠢的職位。 – SHB

回答

0

應設置GridBagLayout的某些屬性來初始化佈局的背景網格:

columnWeights 
columnWidths 
rowWeights 
rowHeights 

而且這是不壞的整體框架佈局改變從FlowLayoutBorderLayout

f.setLayout(new BorderLayout()); 

你改變你的代碼就像這個樣本,它會工作:

//frame task 
f.setLayout(new BorderLayout()); 
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
GridBagLayout bagLayout = new GridBagLayout(); 

bagLayout.columnWeights = new double[]{1.0,1.0,1.0,1.0,1.0}; 
bagLayout.columnWidths = new int[]{25,25,25,25,25}; 
bagLayout.rowWeights = new double[]{1.0,1.0,1.0,1.0,1.0}; 
bagLayout.rowHeights = new int[]{25,25,25,25,25}; 
p.setLayout(bagLayout); 

gbc.gridx=0; 
gbc.gridy=0; 
gbc.gridwidth=3; 
gbc.gridheight=5; 
gbc.fill = GridBagConstraints.BOTH; 

另外GridBagConstraints#fill在使用GridBagLayout時,屬性在確定組件大小時起着重要作用。

如果你想看到一些具體的例子: SWING - GridBagLayout Class

好運

+0

感謝您的回答 – SHB

+0

歡迎您。如果它有幫助並解決了您的問題,您可以通過檢查綠色複選標記來接受它作爲答案。 – STaefi

+0

f.setLayout(new BorderLayout());在默認情況下在API中有(JFrame)BorderLayout – mKorbel

1

答案很簡單,有...

Do you see what I see

這裏是證明...

Proof

你可能有更好的運氣,如果你使用的JTextArea(int, int)構造和使用JScrollPane,例如...

Maybe a better idea

public ServerTest() { 
    //... 
    ta = new JTextArea(10, 20); 
    //... 
    p.add(new JScrollPane(ta), gbc); 
} 
+0

謝謝..我弄錯了.. – SHB

相關問題