在 JFrame 上对齐 JButton 和 JLabel

Aligning the JButton and JLabel on JFrame

我正在尝试创建一个 JFrame,我希望其中的按钮(Select 设备)位于顶部,文本消息(活动)以标签的形式位于底部。我做不到,他们都排在同一条线上。

    JFrame f= new JFrame("AutoV");
    f.setVisible(true);
    f.setSize(600,400);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel p=new JPanel();
    p.setBackground(Color.gray);

    JButton b=new JButton("Select the Device");
    JLabel lab=new JLabel("Active");
    lab.setVerticalAlignment(SwingConstants.BOTTOM);

    //p.add(b);
    p.add(lab);
    p.setBorder(BorderFactory.createLineBorder(Color.black));

    f.add(p);
    Dimension dim1 = Toolkit.getDefaultToolkit().getScreenSize();
    f.setLocation(dim1.width/2-f.getSize().width/2, dim1.height/2-f.getSize().height/2);

您应该查找不同的布局。很多组件的默认布局是FlowLayout,只是让所有元素水平对齐,而且尽量小。将面板布局设置为框或网格布局应该可以解决问题。

https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html