问题
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