0

I want to write a simple Java program, which consists of a JFrame that integrates a JScrollPane. Just it does not work the way I do it.

What is the issue of the my approach ?

public class TestView {

    JFrame frame;
    JScrollPane scrollPane;

    public TestView(){

        frame = new JFrame();
        scrollPane = new JScrollPane();    
        scrollPane.add(new JLabel("Klick me"));
        scrollPane.setMinimumSize(new Dimension(200,200));

        frame = new JFrame();
        frame.getContentPane().add(scrollPane);
        frame.setSize(200,200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void createAndShowGui(){
        TestView tv = new TestView();
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 createAndShowGui();
            }
        });
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3703592
  • 160
  • 8

2 Answers2

2

If the issue is that you do not see your label in the scrollpane, you might need to use

scrollpane.setViewportView(new JLabel("Klick me"));

instead of

scrollPane.add(new JLabel("Klick me"));

Additionally, I suggest you create a JPanel, give it a layout, and place your label there, instead of passing the label to the scrollpane. Then set this panel as the viewport.

Please see

Difference between JscrollPane.setviewportview vs JscrollPane.add

Community
  • 1
  • 1
milez
  • 2,201
  • 12
  • 31
1

use for example:

final JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(50, 50));  
final JScrollPane scrollPane = new JScrollPane(myPanel);

setMinimumSize will be ignored.

12dollar
  • 645
  • 3
  • 17
  • See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Jul 13 '15 at 13:03