java组件怎么靠左对齐,如何在Java Swing中对齐组件?

I'm building a simple beginner app in Java and I need your help with aligning components. What I'm trying to do is to align component(JLabel "name") to the left side of the panel. I've already tried with "new FlowLayout(FlowLayout.LEFT)" but it didn't work so I'm asking you to help me. Here is the picture of the frame and source code below it.

public class firstClass extends JFrame implements ActionListener {

private JFrame frame1;

private JFrame frame2;

private JPanel mainPanelFirst;

private JPanel secondPanel;

private JButton newWindowButton;

private int mulitplyPanels;

private JLabel leftLabel;

private JLabel rightLabel;

private JComboBox leftCB;

private JComboBox rightCB;

First Window:

DhXXM.png

public JFrame createMainUI(){

frame1 = new JFrame("Main frame");

frame1.setSize(600,600);

frame1.setResizable(false);

frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

frame1.setVisible(true);

mainPanelFirst = new JPanel();

mainPanelFirst.setLayout(new FlowLayout());

frame1.add(mainPanelFirst);

newWindowButton = new JButton("Open new window");

newWindowButton.addActionListener(this);

mainPanelFirst.add(newWindowButton);

return frame1;

}

Second Window(include the label I want to align):

VRIFr.png

public JFrame createSecondUI() {

frame2 = new JFrame("Second frame");

frame2.setSize(600, 600);

frame2.setResizable(false);

frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

frame2.setVisible(true);

secondPanel = new JPanel();

secondPanel.setLayout(new FlowLayout());

secondPanel.setBackground(Color.gray);

frame2.add(secondPanel);

JPanel topPanel = new JPanel();

topPanel.setLayout(new FlowLayout(70,400,20));

topPanel.setBackground(Color.WHITE);

secondPanel.add(topPanel);

leftLabel = new JLabel("Name:");

topPanel.add(leftLabel);

return frame2;

}

@Override

public void actionPerformed(ActionEvent e) {

createSecondUI();

}

}

Thank you for your help :)

解决方案

Since that the JFrame is non-resizable, give the topPanel a defined size:

JPanel topPanel = new JPanel();

topPanel.setPreferredSize(new Dimension(600,100));

topPanel.setLayout(new FlowLayout(FlowLayout.LEFT,400,20));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值