Add a JScrollPane to a JFrame

14,387

Solution 1

By Default, JFrame has Borderlayout. BorderLayout have five flags. When you will not specify any flag, It will add you component to frame with center flag. Center flag give all space to component which is added with center flag, if no other flag is specified with component. for more information on border layout, visit following link: http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

You can add both by using following statement:

JFrame frame = new JFrame();

frame.add(new JPanel(), BorderLayout.NORTH);

frame.add(new JScrollpane(), BorderLayout.CENTER);

Solution 2

GridBagLayout is not good for this situation. With lesser code you can get desired Code.

JPanel pnlButton = new JPanel(new FlowLayout(FlowLayout.CENTER));
pnlButton.add(button1);
pnlButton.add(button2);

JFrame frame = new JFrame();
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(pnlButton, BorderLayout.PAGE_END);

If you want to go only with Gridbaglayout. Then you will have to set weightX, weightY, gridwidth and other properties like that

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx=1.0;
gbc.weighy=1.0;
gbc.fill = GridBagConstraints.BOTH;
guiPanel.add(scrollPane, gbc);
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE
guiPanel.add(buttons, gbc);        
guiFrame.add(guiPanel, BorderLayout.CENTER);
guiFrame.setVisible(true);

Please try and let me know, if it does not work, I will send complete code with GridBaglayout.

Share:
14,387
user2351151
Author by

user2351151

Updated on June 14, 2022

Comments

  • user2351151
    user2351151 almost 2 years

    I have a question in relation to adding components to a Java frame.

    I have a JPanel with two buttons and also a JScrollPane that has a JTable added to it. I am wanting to add both these to a JFrame.

    I can add either the JPanel to the JFrame, or the JScrollPane to the JFrame and they display correctly. I am having trouble adding them both to the JFrame and displaying them both.

    Is there something related to JFrames that do not allow this? Any help will be appreciated.

    EDIT

    The problem is not with the layout (at least I do not think that it is), the problem is that the ScrollPane is not displaying correctly. Here is an image to show what I mean:

    http://canning.co.nz/Java/ScrollPane.png

    Here is the code:

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        guiPanel.add(scrollPane, gbc);
        guiPanel.add(buttons, gbc);        
    
        guiFrame.add(guiPanel, BorderLayout.CENTER);
        guiFrame.setVisible(true);