如何在java中添加新行?我可以改变框架的宽度,但如果用户手动展开它,所有控件将显示在同一行。
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);
}
}
感谢您的链接!这工作。
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);
}
}