1,简介
JScrollPane是一个滚动面板,只能添加一个组件(例如在Swing中,像JTextArea、JList、JTable等组件),但是我们可以添加一个面板JPanel,
然后再把很多组件添加到JPanel上。
2,布局
a,边界布局BorderLayout中,发现添加JPanel时,发现不能使用add()方法
例如:
//添加Jscrollpane滚动,只能用
JScrollPane scrollPane = new JScrollPane(panel);
//不能使用
//scrollPane.add(panel);
b,代码如下:
/**
* Create the frame.
*/
public JScrollPaneTest2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300); //位置(100 ,100)宽:450,高300
contentPane = new JPanel();
//Border描述了面板四周的边界(属于面板内部),EmptyBorder为5的一个空白的边界;
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0)); //边界布局
setContentPane(contentPane);
//添加新的JPanel到JScrollPane下
JPanel panel = new JPanel();
int x = 5; //列:5
int y = 5; //行:5
panel.setLayout(new GridLayout(x, y));
for (int i = 0; i < x * y; i++) {
//设置宽100,高100的JButton
JButton button = new JButton(String.valueOf(i));
button.setPreferredSize(new Dimension(100, 100));
panel.add(button);
//添加按钮动作监听
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(button.getText());
}
});
}
//添加Jscrollpane滚动,只能用
JScrollPane scrollPane = new JScrollPane(panel);
//不能使用
//scrollPane.add(panel);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
c,显示
发现窗口在缩小时,没有变化,但是放大时:JButton的宽拉伸了。
3,浮动布局
a,发现直接使用浮动布局行不通,发现股东消失,要修改代码
/**
* Create the frame.
*/
public JScrollPaneTest2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300); //位置(100 ,100)宽:450,高300
contentPane = new JPanel();
//Border描述了面板四周的边界(属于面板内部),EmptyBorder为5的一个空白的边界;
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//添加新的JPanel到JScrollPane下
JPanel panel = new JPanel();
int x = 5; //列:5
int y = 5; //行:5
panel.setLayout(new GridLayout(x, y));
for (int i = 0; i < x * y; i++) {
//设置宽100,高100的JButton
JButton button = new JButton(String.valueOf(i));
button.setPreferredSize(new Dimension(100, 100));
panel.add(button);
//添加按钮动作监听
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(button.getText());
}
});
}
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
//先把panel添加到contentPane
contentPane.add(panel);
//添加Jscrollpane滚动,只能用
JScrollPane scrollPane = new JScrollPane(contentPane);
//最后添加上scrollPane
setContentPane(scrollPane);
}
b,显示
发现窗口变化时JButton的长宽没有变化。