JScrollPane 滚动条不起作用的问题

fei得更高 2020-06-30 03:52:04

import java.awt.Color;
import java.awt.Container;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class MainFrame extends JFrame
{

/**
*
*/
private static final long serialVersionUID = 1L;

private final int ROW_HEIGHT = 30;
private final int NUM_WIDTH = 50;
private final int OP_WIDTH = 150;

private JScrollPane scroll = new JScrollPane();
private JPanel panel = new JPanel();
private Container container;
private Map<Integer, JPanel> rowMap = new HashMap<Integer, JPanel>();

public MainFrame()
{
this.setSize(800, 600);
this.setTitle("测试一下滚动");
container = this.getContentPane();
container.setLayout(null);
scroll.setBounds(10, 10, 400, 300);
scroll.setBorder(BorderFactory.createLineBorder(Color.black));
panel.setLayout(null);
panel.setBounds(0, 0, 400, 600);
scroll.setViewportView(panel);
addRow();
for (int i = 0; i < 20; i++)
{
addRow();
}
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
container.add(scroll);
this.setVisible(true);
}

private void addRow()
{
int targetRowIndex = rowMap.size();
JPanel rowPanel = new JPanel();
rowPanel.setLayout(null);
int beginY = ROW_HEIGHT * targetRowIndex;
rowPanel.setBounds(0, beginY, 300, ROW_HEIGHT);
JLabel label = new JLabel();
label.setText(targetRowIndex + "");
label.setBounds(0, 0, NUM_WIDTH, ROW_HEIGHT);
rowPanel.add(label);
label = new JLabel();
label.setText("添加");
label.setForeground(Color.BLUE);
label.setBounds(NUM_WIDTH, 0, OP_WIDTH, ROW_HEIGHT);
rowPanel.add(label);
rowMap.put(targetRowIndex, rowPanel);
panel.add(rowPanel);
}
}

上面的代码运行之后,发现滚动面板的滚动不起作用,请教大伙,这个是什么原因造成的?
...全文
93 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧