如何在 Java 中结合使用 FlowLayout 和 BoxLayout?\n
要组合两种布局,我们在此创建两个面板 -
Frame f = new JFrame("Combining Layouts");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();现在,相应地设置布局 -
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS)); panel2.setLayout(new FlowLayout());
然后在向两个面板添加组件后,将它们添加到框架 -
f.add(panel1, BorderLayout.WEST); f.add(panel2, BorderLayout.CENTER);
示例
package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SwingDemo {
public static void main(String[] args) {
JFrame f = new JFrame("Combining Layouts");
JPanel panel1 = new JPanel();
panel1.setLayout(new BoxLayout(panel1, BoxLayout.Y_AXIS));
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout());
panel2.setBackground(Color.red);
panel1.add(new JTextArea("TextArea1"));
panel1.add(new JTextArea("TextArea2"));
panel1.add(new JTextArea("TextArea3"));
panel1.add(new JTextArea("TextArea4"));
panel1.add(new JTextArea("TextArea5"));
panel1.add(new JTextArea("TextArea6"));
panel1.add(new JTextArea("TextArea7"));
panel2.add(new JLabel("JLabel1"));
panel2.add(new JLabel("JLabel2"));
panel2.add(new JLabel("JLabel3"));
panel2.add(new JLabel("JLabel4"));
panel2.add(new JLabel("JLabel5"));
panel2.add(new JLabel("JLabel6"));
panel2.add(new JLabel("JLabel7"));
f.add(panel1, BorderLayout.WEST);
f.add(panel2, BorderLayout.CENTER);
f.setVisible(true);
f.setSize(550, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP