Incorrect position of Swing components

空扰寡人 提交于 2020-01-17 14:17:08

问题


I woud like to have button btn at the bottom of a JFrame. I have this in right side. Where is bug in my code?

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);
    }
}

回答1:


BoxLayout.Y_AXIS. Vis.

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();
            }
        });
    }
}



回答2:


You should use BoxLayout.Y_AXIS instead of X_AXIS:

Components are laid out vertically from top to bottom.




回答3:


JFrame has implemented BorderLayout by default, if you want to put JButton to the bottom of JFrame, then you have to define add(new JButton("btn", BorderLayout.SOUTH));



来源:https://stackoverflow.com/questions/9259153/incorrect-position-of-swing-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!