1、JPanel面板
JPanel组件作为容器类,除了可以添加组件外,也可以设置布局管理器,将面板中的组件布局。
package Eleven;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JPanelTest extends JFrame{
public JPanelTest(){
Container container = getContentPane();
container.setLayout(new GridLayout(2,2,10,10));
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("2"));
p1.add(new JButton("3"));
p2.add(new JButton("1"));
p2.add(new JButton("2"));
p3.add(new JButton("1"));
p3.add(new JButton("2"));
p4.add(new JButton("1"));
p4.add(new JButton("2"));
container.add(p1);
container.add(p2);
container.add(p3);
container.add(p4);
setVisible(true);
/*void java.awt.Window.pack();
Causes this Window to be sized to fit
the preferred size and layouts of its
subcomponents. The resulting width and
height of the window are automatically
enlarged if either of dimensions is less
than the minimum size as specified by the
previous call to the setMinimumSize method
*/
pack();
}
public static void main(String[] args){
new JPanelTest();
}
}
2、JScrollPane
带滚动条的面板,常用于布置单个组件,不可以使用布局管理器。需要在JScrollPane中放入多个组件时,需要将多个组件放置在JPanel面板上,再将JPanel面板作为一个整体组件添加到JScrollPane组件上。
package Eleven;
/*JScrollPane是一种容器,但其常用于布置单个组件,并且不可以使用布局管理器,
* 若需要在其上添加多个组件,需要将多个组件放置在JPanel面板上,然后将JPanel面板
* 作为一个整体组件添加到JSrollPanel组件上*/
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
public class JScrollPaneTest extends JFrame {
public JScrollPaneTest(){
Container container = getContentPane();
JTextArea textArea = new JTextArea(20,50);
//javax.swing.JScrollPane.JScrollPane(Component view)
/*Parameters:
view the component to display in the scrollpane's viewport*/
JScrollPane scrollPane = new JScrollPane(textArea);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//textArea.setText(str);
container.add(scrollPane);
setTitle("带滚动条的文字编辑器");
setSize(200,200);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new JScrollPaneTest();
}
}