62,614
社区成员
发帖
与我相关
我的任务
分享
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);
}
}