Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JPanel scrollable?

I'm creating GUI for my university project and I 'm trying to understand how JScrollPane works.

I have successfully written simple program which shows picture in a scrollable way:

public class ScrollPaneTest{
    public static void main(String[] args){
        JFrame testFrame = new JFrame("ramka testowa");
        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel picture = new JLabel(new ImageIcon("JavaSwingCompoentsList.PNG"));
        JScrollPane scrollPane = new JScrollPane(picture);

        testFrame.add(scrollPane, BorderLayout.CENTER);
        testFrame.setSize(400, 400);
        testFrame.setVisible(true);
    }
}

Although, in my final GUI, I would like to apply JScrollPane only to a part of it, e.g. single JPanel. To test this idea I have written following code, which unfortunately does not work:

public class ScrollPaneTest{
    public static void main(String[] args){
        JFrame testFrame = new JFrame("ramka testowa");
        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel picture = new JLabel(new ImageIcon("JavaSwingCompoentsList.PNG"));
        JScrollPane scrollPane = new JScrollPane(picture);

        JPanel insidePanel = new JPanel();
        insidePanel.add(scrollPane);
        testFrame.add(insidePanel, BorderLayout.CENTER);

        testFrame.setSize(400, 400);
        testFrame.setVisible(true);

    }
}

I have read numerous tutorials, as well as Stack and CodeRanch articles and I still fail to grasp the idea of how the JScrollPane work. I suspect, that my mistake has something to do with specifying the dimension of JPanel-to-scroll, but every single approach I have tried gave me no scrollbars or no picture at all.

If you could show me the right solution to this problem and most importantly, show me where I was wrong I would be very grateful.

like image 914
Karol Pokomeda Avatar asked Dec 19 '25 00:12

Karol Pokomeda


2 Answers

  1. Initialize JPanel, not JScrollPane with picture
  2. To add the JPanel to JScrollPane, do:

    scrollPane.setViewportView (panel)
    
  3. Add the JScrollPane, not JPanel to the JFrame

like image 139
Top Sekret Avatar answered Dec 21 '25 14:12

Top Sekret


The simplest way is to create your JPanel and specify it when creating the JScrollPane:

 JPanel myPanel = ...;
 JScrollPane scroller = new JScrollPane( myPanel );

Then just add the scroller to your GUI (instead of adding myPanel ).

like image 45
FredK Avatar answered Dec 21 '25 12:12

FredK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!