Torewin
Torewin

Reputation: 64

Java adding JLabels to Panel embedded in 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);

I'm trying to add these labels to the panel that is embedded in a scrollPane. The labels are display correctly except for when the last few are over the size of the panel. The scrollPane does not scroll. I have tried .setLayout to various different layouts and still no results. Am I missing something on how to do this?

Upvotes: 0

Views: 746

Answers (1)

KyleKW
KyleKW

Reputation: 300

Okay I got this working with 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);

}

You can change around the values, this is very rough. Hope this helps!

Upvotes: 1

Related Questions