简体   繁体   中英

how to add new line in java

How do you add a new line in java. I can change the width of the frame but if the user manually expands it, all the controls display on the same line.

import java.awt.*;
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;


public class test {
    
    public static void main(String[] args) {
        JFrame f = new JFrame("Hello");

        JPanel MyPanel = new JPanel();

        MyPanel.setLayout(new FlowLayout()); // Demo flow layout

        JLabel l1 = new JLabel("label 1");
        JTextField t1 = new JTextField(10);
        JLabel l2 = new JLabel("label 2");
        JTextField t2 = new JTextField(10);

        MyPanel.add(l1); // Add JButtons using Flow Layout
        MyPanel.add(t1);
        MyPanel.add(l2);
        MyPanel.add(t2);

        // Paste MyPanel in center of the contentPane  
        f.getContentPane().add(MyPanel, "Center");   
        f.setSize(400, 300);
        f.setVisible(true);
    }
}

Thank you for the link. this works.

import java.awt.Container;  
import javax.swing.GroupLayout;  
import javax.swing.JLabel;  
import javax.swing.JTextField;  
import javax.swing.JFrame;  
import static javax.swing.GroupLayout.Alignment.*;  
public class test {  
    public static void main(String[] args) {  
        JFrame frame = new JFrame("GroupLayoutExample");  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        Container myPanel = frame.getContentPane();  
  
        GroupLayout groupLayout = new GroupLayout(myPanel);  
        groupLayout.setAutoCreateGaps(true);  
        groupLayout.setAutoCreateContainerGaps(true);  
        myPanel.setLayout(groupLayout);  
  
     JLabel l1 = new JLabel("label 1");
         JTextField t1 = new JTextField(10);
     JLabel l2 = new JLabel("label 2");
         JTextField t2 = new JTextField(10);
  
        groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()  
                .addGroup(groupLayout.createParallelGroup(LEADING).addComponent(l1).addComponent(l2))  
                .addGroup(groupLayout.createParallelGroup(TRAILING).addComponent(t1).addComponent(t2)));  
  
        groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()  
                .addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(l1).addComponent(t1))  
                .addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(l2).addComponent(t2)));  
  
        frame.pack();  
        frame.setVisible(true);  
    }  
}  

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