【问题标题】:Aligning the JButton and JLabel on JFrame在 JFrame 上对齐 JButton 和 JLabel
【发布时间】:2015-10-20 16:54:43
【问题描述】:

我正在尝试创建一个 JFrame,我希望按钮(选择设备)位于顶部,文本消息(活动)以标签的形式位于底部。我无法做到这一点,他们都在同一条线上并排出现。

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

【问题讨论】:

  • 1. JPanel 有 FLowLayout 和 2. f.setVisible(true);必须是那里的最后一行代码,3
  • 控制位置是由布局控制的,画布你用的是哪一个?
  • @RomanC 正如@mKorbel 所说,默认布局是FlowLayout,因为提问者没有设置任何其他内容。此外,Swing 中没有画布 :)
  • 此程序中没有画布。我只需要对齐按钮和标签。

标签: java swing jframe jbutton jlabel


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 2017-02-21
    • 1970-01-01
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多