Swing组件的位置不正确

时间:2012-02-13 10:48:29

标签: java swing jframe jbutton layout-manager

我想在btn底部设置按钮JFrame。我有这个在右边。我的代码中的bug在哪里?

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 个答案:

答案 0 :(得分: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();
            }
        });
    }
}

答案 1 :(得分:2)

您应该使用BoxLayout.Y_AXIS代替X_AXIS

  

组件从上到下垂直布置。

答案 2 :(得分:1)

默认情况下,

JFrame已实施BorderLayout,如果您想将JButton放在JFrame的底部,则必须定义add(new JButton("btn", BorderLayout.SOUTH));