2015-11-14 46 views
1

我想問我的代碼是否有任何問題。我用borderlayout設置了我的框架。在中心部分,我想用gridlayout,裏面有7個箭頭和2個cols。jpanel無法使7行和2列的網格佈局

 paneltengah= new JPanel(); 
     paneltengah.setLayout(new GridLayout(7,2)); 


     labelname = new JLabel(lbl_name,SwingConstants.LEFT);  
     labelusername = new JLabel(lbl_username,SwingConstants.LEFT);                   
     labelpassword = new JLabel(lbl_password,SwingConstants.LEFT);    
     labelgender = new JLabel(lbl_gender,SwingConstants.LEFT);    
     labelemail = new JLabel(lbl_email,SwingConstants.LEFT);   
     labelhobby = new JLabel(lbl_hobby,SwingConstants.LEFT);    
     labelrole = new JLabel(lbl_role,SwingConstants.LEFT); 

     textname = new JTextField(20); 
     textusername = new JTextField(20); 
     textpassword = new JPasswordField(20); 
     textemail = new JTextField(20); 
     comboboxhobby = new JComboBox(); 
     comboboxrole = new JComboBox(); 
     radiobuttonmale = new JRadioButton("Male"); 
     radiobuttonfemale = new JRadioButton("Female"); 
     ButtonGroup btngroup = new ButtonGroup(); 
     btngroup.add(radiobuttonmale); 
     btngroup.add(radiobuttonfemale); 



     paneltengah.add(labelname); 
     paneltengah.add(labelusername); 
     paneltengah.add(labelpassword); 
     paneltengah.add(labelgender); 
     paneltengah.add(labelemail); 
     paneltengah.add(labelrole); 
     paneltengah.add(labelhobby); 

////  paneltengah.add(textname); when i open this, the layout become awkward  
////  paneltengah.add(textusername); 
////  paneltengah.add(textpassword); 
////  paneltengah.add(radiobuttonmale); 
////  paneltengah.add(radiobuttonfemale); 
////  paneltengah.add(comboboxhobby); 
////  paneltengah.add(comboboxrole); 


     pane.add(paneltengah, BorderLayout.CENTER);  

下面的圖片顯示,而無需打開評論

enter image description here

如下圖所示與取消註釋

enter image description here

什麼是錯我的代碼?

回答

0

首先,GridLayout將所有組件的尺寸均勻地分配到其關聯的Container中,這就解釋了爲什麼您的標籤和字段的尺寸都是相同的。例如,如果您的JPanel中有JTextArea 200列×20行,那麼即使是最小的標籤也會佔用這麼大的空間!

接着,根據GridLayout的Javadoc,當GridLayout實例構造有兩個非零參數,行數被固定,並且根據投入的父Container部件的數量調整的列數。

我建議使用BorderLayout來設置主窗體佈局。把你的標題NORTH並保持CENTER爲標籤和字段(您當前JPanel)。

爲標籤和領域,最簡單的解決辦法可能是使用GridLayout(0, 2)(列固定數量)。但是,所有組件的大小仍然相同。

如果你需要在你的組件(例如,字段比標籤寬)的大小更多的控制,那麼我建議使用另一種佈局管理器如GridBagLayout。我知道管理起來比較複雜,但使用GridBagLayout格式預覽工具應該有所幫助。這樣的程序可能被命名爲GridBagLab(我知道David Geary的書圖形Java第2卷 - Swing在它的伴隨CD上具有一個特徵)。

還有GridBagLayout教程https://www.youtube.com/watch?v=Ts5fsHXIuvI