简体   繁体   English

在JFrame上对齐JButton和JLabel

[英]Aligning the JButton and JLabel on JFrame

I am trying to create a JFrame and in which I want the button (Select the Device) to be on top and a text message (Active) which is in the form of Label at the bottom. 我正在尝试创建一个JFrame,在其中我希望按钮(选择设备)位于顶部,文本消息(活动)位于底部,标签形式。 I am unable to do that and they are all coming up in the same line next to each other. 我无法做到这一点,他们都排在同一行。

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

You should look up different layouts. 您应该查找不同的布局。 The default layout of many components is FlowLayout, witch just aligns all elements horizontally, and as small as possible. 许多组件的默认布局是FlowLayout,witch只是将所有元素水平对齐并尽可能地小。 Setting the panels layout to box or grid layout should do the trick. 将面板布局设置为方框或网格布局应该可以解决问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM