Search code examples
javaswingscrollcomponentsjscrollpane

JScrollPane components do not appear


I'm trying to put some components inside of a JScrollPane but every time I launch my program they don't appear. I just started learning about GUIs today so I figure I missed something small but no matter where I look online I can't find an answer. The only thing that appears is the JScrollPane itself.

class MainFrame extends JFrame{
    public MainFrame(String title){
        //Main Frame Stuff
        super(title);
        setSize(655, 480);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        //Layout
        FlowLayout flow = new FlowLayout();
        setLayout(flow);

        //Components
        JButton spam_button = new JButton("Print");
        JLabel label = new JLabel("What do you want to print?",
                                  JLabel.LEFT);
        JTextField user_input = new JTextField("Type Here", 20);

        //Scroll Pane
        JScrollPane scroll_pane = new JScrollPane(
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scroll_pane.setPreferredSize(new Dimension(640, 390));

        //Adding to Scroll
        scroll_pane.add(label);
        scroll_pane.add(user_input);
        scroll_pane.add(spam_button);

        //Adding to the Main Frame
        add(scroll_pane);

        //Visibility
        setVisible(true);
    }
}

The point of the program is to print whatever you type 100 times but I haven't gotten that far yet because I've been hung up on this scroll problem. When I finally get things to show up in the scroll pane I'm going to move those three components to a JPanel above the scroll pane and then I'm going to add the 100 words to the scroll pane so that you can scroll through it.


Solution

  • I just started learning about GUIs today

    So the first place to start is with the Swing tutorial. There is plenty of demo code to download and test and modify.

    scroll_pane.add(label);
    scroll_pane.add(user_input);
    scroll_pane.add(spam_button);
    

    A JScrollPane is not like a JPanel:

    1. you don't add components directly to the scroll panel. You add a component to the viewport of the scroll pane
    2. only a single component can be added to the viewport.

    So your code should be something like:

    JPanel panel = new JPanel();
    panel.add(label);
    panel.add(user_input);
    panel.add(spam_button);
    scrollPane.setViewportView( panel );