【javaSE】JPanel+FLowLayout加垂直滚动条...

dosgege 2012-05-05 11:07:38
代码
class ModifiedFlowLayout extends FlowLayout {

public ModifiedFlowLayout() {
super();
}

public ModifiedFlowLayout(int align) {
super(align);
}

public ModifiedFlowLayout(int align, int hgap, int vgap) {
super(align, hgap, vgap);
}

public Dimension minimumLayoutSize(Container target) {
return computeSize(target, false);
}

public Dimension preferredLayoutSize(Container target) {
return computeSize(target, true);
}

private Dimension computeSize(Container target, boolean minimum) {
synchronized (target.getTreeLock()) {
int hgap = getHgap();
int vgap = getVgap();
int w = target.getWidth();

if (w == 0) {
w = Integer.MAX_VALUE;
}

Insets insets = target.getInsets();
if (insets == null) {
insets = new Insets(0, 0, 0, 0);
}
int reqdWidth = 0;

int maxwidth = w - (insets.left + insets.right + hgap * 2);
int n = target.getComponentCount();
int x = 0;
int y = insets.top;
int rowHeight = 0;

for (int i = 0; i < n; i++) {
Component c = target.getComponent(i);
if (c.isVisible()) {
Dimension d =
minimum ? c.getMinimumSize() : c.getPreferredSize();
if ((x == 0) || ((x + d.width) <= maxwidth)) {
if (x > 0) {
x += hgap;
}
x += d.width;
rowHeight = Math.max(rowHeight, d.height);
} else {
x = d.width;
y += vgap + rowHeight;
rowHeight = d.height;
}
reqdWidth = Math.max(reqdWidth, x);
}
}
y += rowHeight;
return new Dimension(reqdWidth + insets.left + insets.right, y);
}
}
}

public class SimpleTest extends JPanel{
private ImageIcon image;
private JLabel label;
private JButton button;
private JPanel buttonPanel, imagePanel;
private JScrollPane scrollPane;

public SimpleTest(){
this.setLayout(new BorderLayout());

button = new JButton("Add Image");
button.setPreferredSize(new Dimension(80, 25));
button.setMargin(new Insets(0, 5, 0, 5));

image = new ImageIcon("E:\\tobacco\\img\\folder.png");
imagePanel = new JPanel(new ModifiedFlowLayout(FlowLayout.LEFT, 5, 5));
for(int i=0;i<12;i++)
{
label = new JLabel(image);
//label.setPreferredSize(new Dimension(100,100));//为什么添加此句,滚动条显示错误?
imagePanel.add(label);
}

scrollPane = new JScrollPane(imagePanel);

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){

label = new JLabel(image);
imagePanel.add(label);
validate();
}
});

buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
buttonPanel.add(button);

add(buttonPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
}

public static void main(String[] args) {
JFrame jf =new JFrame();
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
jf.setBounds(200,50,480,300);


jf.add(new SimpleTest());

jf.setVisible(true);
}
}


问题:当设置面板中组件的preferredSize后,滚动条显示就有问题?具体看第2个类的代码注释行。

求解释,求解决办法!
...全文
116 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

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

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