2012-02-13 101 views
-1

我希望在JFrame的底部有按鈕btn。我有這個在右側。我的代碼中的錯誤在哪裏?Swing組件的位置不正確

class MainClass extends JFrame { 

    private JSplitPane splitPan=null; 

    private void treePanel(){ 

     DefaultMutableTreeNode nod=new DefaultMutableTreeNode("AAA",true); 
     nod.add(new DefaultMutableTreeNode("abcd")); 

     JTree tree=new JTree(nod); 

     JScrollPane scroll=new JScrollPane(tree); 

     splitPan=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll,new JLabel("aaaaa")); 
     splitPan.setSize(this.getMaximumSize()); 

     add(splitPan); 
    } 


    public MainClass() { 

     setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); 

     treePanel();  
     add(new JButton("btn")); 

     pack(); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setSize(300,200); 
     setVisible(true); 
    } 
} 

回答

3

BoxLayout.Y_AXIS。可見。

MainClass

import javax.swing.*; 
import javax.swing.tree.*; 

class MainClass extends JFrame { 

    private JSplitPane splitPan=null; 

    private void treePanel(){ 
     DefaultMutableTreeNode nod=new DefaultMutableTreeNode("AAA",true); 
     nod.add(new DefaultMutableTreeNode("abcd")); 
     JTree tree=new JTree(nod); 
     JScrollPane scroll=new JScrollPane(tree); 
     splitPan=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll,new JLabel("aaaaa")); 
     splitPan.setSize(this.getMaximumSize()); 
     add(splitPan); 
    } 

    public MainClass() { 
     // this is it! 
     setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); 
     treePanel(); 
     add(new JButton("btn")); 
     pack(); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setSize(300,200); 
     setVisible(true); 
    } 

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

簡單/漂亮/實例1 – mKorbel 2012-02-13 11:06:34

1

JFrame已實施BorderLayout默認情況下,如果你想要把JButtonJFrame底部,那麼你必須定義add(new JButton("btn", BorderLayout.SOUTH));

2

您應該使用BoxLayout.Y_AXIS而不是X_AXIS

組件從上到下垂直佈局。

+0

盒接受XxxSize從JComponent的1 – mKorbel 2012-02-13 10:57:49