2016-11-11 124 views
0
import javax.swing.*; 
import java.awt.*; 

class MyJPanel extends JPanel { 
JButton login, register; 

public MyJPanel() { 
    login = new JButton("Login"); 
    register = new JButton("Register"); 

    this.add(register); 
    this.add(login); 
} 
} 

class MyJFrame extends JFrame { 
MyJPanel mjp; 

public MyJFrame(String title) { 
    super(title); 

    mjp = new MyJPanel(); 

    Container ct = getContentPane(); 
    ct.add(mjp); 


    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); 
    setSize(400,400); 
    this.setVisible(true); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
} 
} 

class Gui7FirstPage { 
public static void main(String[] args) { 
    MyJFrame mjf = new MyJFrame("Welcome!"); 
} 
} 

不工作上面的代码被对齐2个按钮登录和沿X轴的寄存器。我打算使用BoxLayout.Y_AXIS将它们堆叠起来,但它似乎不起作用。BoxLayout.Y_AXIS在秋千

2个按钮水平并排排列,我希望它们能够正确放置。

回答

1

默认情况下,JPanel使用FlowLayout,因此您的MyJPanel类正在使用FlowLayout

您正在将按钮添加到面板,因此面板需要使用BoxLayout而不是内容窗格。

在构造函数类的开始,你需要:

setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));