如何在Java Swing中对齐组件? [英] How do I align components in Java Swing?

查看:210
本文介绍了如何在Java Swing中对齐组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java构建一个简单的初学者应用程序,我需要您在对齐组件方面的帮助.我想做的是将组件(JLabel名称")对准面板的左侧.我已经尝试过使用"new FlowLayout(FlowLayout.LEFT)",但是它没有用,所以我想请您帮忙.这是框架的图片及其下面的源代码.

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;

第一个窗口:

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

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

    }
}

谢谢您的帮助:)

推荐答案

警告也请阅读:我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法吗?

由于JFrame是不可调整大小的,因此请给topPanel定义大小:

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

这篇关于如何在Java Swing中对齐组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆