2014-04-10 37 views
0

我想實現這個佈局我要如何單獨的JPanel中的JFrame

enter image description here

我不知道爲什麼我收到此

enter image description here

這是我的代碼

package testing; 

import java.io.*; 
import java.util.*; 
import java.security.*; 
import javax.xml.bind.DatatypeConverter; 
import java.lang.*; 
import java.awt.*; 
import javax.swing.*; 

public class Testing 
{ 


    public static class GridPanel extends JPanel 
    { 
     public GridPanel() 
     { 
      setLayout(new GridLayout(4,4)); 
      setBackground(Color.GREEN); 
      this.setPreferredSize(new Dimension(500,100)); 



      JButton b1 = new JButton ("Button 1"); 
      JButton b2 = new JButton ("Button 2"); 
      JButton b3 = new JButton ("Button 3"); 
      JButton b4 = new JButton ("Button 4"); 
      JButton b5 = new JButton ("Button 5"); 
      JButton b6 = new JButton ("Button 6"); 
      JButton b7 = new JButton ("Button 7"); 
      JButton b8 = new JButton ("Button 8"); 
      JButton b9 = new JButton ("Button 9"); 
      JButton b10 = new JButton ("Button 10"); 
      JButton b11 = new JButton ("Button 11"); 
      JButton b12 = new JButton ("Button 12"); 
      JButton b13 = new JButton ("Button 13"); 
      JButton b14 = new JButton ("Button 14"); 
      JButton b15 = new JButton ("Button 15"); 
      JButton b16 = new JButton ("Button 16"); 

      add(b1); 
      add(b2); 
      add(b3); 
      add(b4); 
      add(b5); 
      add(b6); 
      add(b7); 
      add(b8); 
      add(b9); 
      add(b10); 
      add(b11); 
      add(b12); 
      add(b13); 
      add(b14); 
      add(b15); 
      add(b16); 

     } 

    } 



    public static void main(String[] args) 
    { 
     JPanel primary = new JPanel(); 
     primary.setPreferredSize(new Dimension(500,500)); 



     JPanel jp1 = new JPanel(); 
     jp1.setPreferredSize(new Dimension(500,100)); 
     JTextField jt1 = new JTextField(8); 
     jp1.add(jt1); 


     GridPanel gp = new GridPanel(); 

     primary.add(jp1); 
     primary.add(gp); 

     JFrame jf = new JFrame(); 
     jf.setPreferredSize(new Dimension(500,500)); 
     jf.add(primary); 
     jf.pack(); 
     jf.setVisible(true); 

    } 


} 

我不知道如何分離在框架中的兩個面板,我怎麼做錯了?

回答

2

嘗試這樣:

public static void main(String[] args) 
{ 

    JPanel primary = new JPanel(new BorderLayout()); 
    primary.setOpaque(true); 

    JTextField jt1 = new JTextField(8); 
    jt1.setPreferredSize(new Dimension(0, 30)); 
    primary.add(jt1, BorderLayout.NORTH); 


    GridPanel gp = new GridPanel(); 
    primary.add(gp, BorderLayout.CENTER); 

    JFrame jf = new JFrame(); 
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    jf.setPreferredSize(new Dimension(400,200)); 
    jf.setContentPane(primary); 
    jf.pack(); 
    jf.setVisible(true); 

} 
+0

@Computernerd:上面給出的主要功能替換你的代碼的主要功能,它的工作原理。 – astack

1

使用BorderLayout查看JFrame,將面板放置在Page_Start部分中的所需文本區域和GridPanel的中央部分中。