第13章 Swing程序设计----常用面板

时间:2023-12-30 08:53:50

面板也是一个Swing容器,它可以作为容器容纳其他组件,但它也必须被添加到其他容器中

Swing常用的面板包括JPanel面板和JScrollPanel面板

1、JPanel面板

 import java.awt.*;

 import javax.swing.*;

 public class JPanelTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L; public JPanelTest() {
Container c = getContentPane();
// 将整个容器设置为2行1列的网格布局
c.setLayout(new GridLayout(2, 1, 10, 10));
// 初始化一个面板,设置1行3列的网格布局
JPanel p1 = new JPanel(new GridLayout(1, 3, 10, 10));
JPanel p2 = new JPanel(new GridLayout(1, 2, 10, 10));
JPanel p3 = new JPanel(new GridLayout(1, 2, 10, 10));
JPanel p4 = new JPanel(new GridLayout(2, 1, 10, 10));
p1.add(new JButton("1")); // 在面板中添加按钮
p1.add(new JButton("1"));
p1.add(new JButton("2"));
p1.add(new JButton("3"));
p2.add(new JButton("4"));
p2.add(new JButton("5"));
p3.add(new JButton("6"));
p3.add(new JButton("7"));
p4.add(new JButton("8"));
p4.add(new JButton("9"));
c.add(p1); // 在容器中添加面板
c.add(p2);
c.add(p3);
c.add(p4);
setTitle("在这个窗体中使用了面板");
setSize(420, 200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
} public static void main(String[] args) {
new JPanelTest();
}
}

第13章 Swing程序设计----常用面板

在该类中创建4个JPanel面板组件,并将其添加到窗体中。

2、JScrollPane面板

在设置界面时,可能遇到在一个较小的容器窗体中显示一个较大部分的内容的情况这是可以使用JScrollPane面板。

JScrollPane面板是带滚动条的面板,它也是一种容器,但是JScrollPane只能放置一个组件,并且不可以使用布局管理器

如果需要在JScrollPane面板中放置多个组件,需要将多个组件放置在JPanel面板上,然后将JPanel面板作为一个整体组件添加在JScrollPane组件上。

 import java.awt.*;

 import javax.swing.*;

 public class JScrollPaneTest extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L; public JScrollPaneTest() {
Container c = getContentPane(); // 创建容器
JTextArea ta = new JTextArea(20, 50); // 创建文本区域组件
JScrollPane sp = new JScrollPane(ta); // 创建JScrollPane面板对象
c.add(sp); // 将该面板添加到该容器中 setTitle("带滚动条的文字编译器");
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new JScrollPaneTest();
}
}

第13章 Swing程序设计----常用面板