Swing组件中不仅有JFrame 和 JDialog 这样的顶级容器,而且提供了一些面板组件(也称为中间容器)。面板组件不能单独存在,只能放置在顶级窗口容器中。最常见的面板组件有两种,分别是JPanel和 JSerollPane,下面分别介绍这两种面板组件。
JPanel
JPanel面板组件是个无边框且不能被移动、放大、缩小或者关闭的面板,它的默认布局管理器是FlowLayout。也可以使用JPanel带参数的构造函数JPanel (LayoutManager layout)或者setLayout()成员方法设置JPanel布局管理器。
JPanel面板组件类并没有包含多少特殊的组件操作方法,大数都是从父类(如 Container)继承过来的,使用也非常简单。
代码实例:
import javax.swing.*;
import java.awt.*;
public class JPanelDemo extends JFrame {
public JPanelDemo(){
Container container = this.getContentPane();
//10,10 参数设置的是间距
container.setLayout(new GridLayout(2,1,10,10));
JPanel panel1 = new JPanel(new GridLayout(1,3));
JPanel panel2 = new JPanel(new GridLayout(2,1));
JPanel panel3 = new JPanel(new GridLayout(3,1));
JPanel panel4 = new JPanel(new GridLayout(1,2));
panel1.add(new Button("1"));
panel1.add(new Button("1"));
panel1.add(new Button("1"));
panel2.add(new Button("2"));
panel2.add(new Button("2"));
panel3.add(new Button("3"));
panel3.add(new Button("3"));
panel3.add(new Button("3"));
panel4.add(new Button("4"));
panel4.add(new Button("4"));
container.add(panel1);
container.add(panel2);
container.add(panel3);
container.add(panel4);
this.setVisible(true);
this.setSize(500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new JPanelDemo();
}
}
运行结果:
JPanelScroll
JScrollPane是一个带有滚动条的面板,面板上只能添加一个组件。如果想向JScrollPane面板中添加多个组件,应该先将多个组件添加到某个组件中,然后将这个组件添加到JScrollPane中。
代码实例:
import javax.swing.*;
import java.awt.*;
public class JScrollDemo extends JFrame {
public JScrollDemo(){
Container container = this.getContentPane();
JTextArea textArea= new JTextArea(20,50);
textArea.setText("欢迎学习狂神说Java");
//Scroll面板
JScrollPane scrollPane = new JScrollPane(textArea);
container.add(scrollPane);
this.setVisible(true);
this.setBounds(100,100,300,350);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new JScrollDemo();
}
}
运行结果: