Java将JLabel添加到ScrollPane中嵌入的Panel

时间:2016-12-13 17:43:10

标签: java jpanel jlabel scrollpane

JScrollPane scrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(23, 11, 603, 123);

contentPane.add(scrollPane);

JPanel panel = new JPanel();
JLabel[] labels=new JLabel[callout.getRedCount()]; //callout.getRedCount() = 8
panel.setLayout(null);
int x = 50;
int y = 50;
for (int i=0;i<callout.getRedCount();i++){ //callout.getRedCount() = 8
        labels[i]=new JLabel("Red" + i);
        labels[i].setBounds(x, y, 32, 32);
        panel.add(labels[i]);
        x += 150;
}
scrollPane.setViewportView(panel);

我尝试将这些标签添加到嵌入scrollPane的面板中。除最后几个超过面板大小的标签外,标签显示正确。 scrollPane不会滚动。我已尝试.setLayout各种不同的布局,仍然没有结果。我错过了关于如何做到的事情吗?

1 个答案:

答案 0 :(得分:0)

好的,我使用了GridBagLayout。

public static void main(String args[]){

    JFrame contentPane = new JFrame();

    JScrollPane scrollPane = new JScrollPane(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setBounds(23, 11, 50, 50);

    contentPane.add(scrollPane);

    JPanel panel = new JPanel();
    JLabel[] labels=new JLabel[8]; //callout.getRedCount() = 8
    panel.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(0,10,0,0);
    int x = 50;
    int y = 50;
    for (int i=0;i<8;i++){ //callout.getRedCount() = 8
            labels[i]=new JLabel("Red" + i);
            gbc.gridx = i;
            panel.add(labels[i], gbc);
    }
    scrollPane.setViewportView(panel);
    contentPane.setSize(50,50);
    contentPane.setVisible(true);

}

您可以更改值,这是非常粗糙。希望这有帮助!