简体   繁体   中英

How do I align components in 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:

https://i.stack.imgur.com/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):

https://i.stack.imgur.com/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 :)

Warning read this as well: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

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

I would suggest using a Layout Manager for your app. The one you're looking for is most likely BorderLayout, unless you want specific abilities to control where and how your objects are laid out.

Hope this helps

Layout Managers

How to use BorderLayout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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