0

I have a JPanel (myPanel) with a lot of button inside (this panel is contained in another panel that contain other components). I would insert this JPanel (myPanel) into a scroll to control better the button.

This is a part of my code:

    JPanel firstPanel = new JPanel(null);
    ......
    ......        
    JPanel myPanel = new JPanel(null);
    myPanel.setBounds(0, position+22, 400, 500);
    for (int i=0; i<size; i++) {
        JButton button = new JButton(myList.get(i));
        if (counter%4 == 0) {
            button.setBounds(270, 0+(4*i), 90, 18);
        } else if (counter%3 == 0) {
            button.setBounds(180, 4+(4*i), 90, 18);
        } else if (counter%2 == 0) {
            button.setBounds(90, 8+(4*i), 90, 18);
        } else {
            button.setBounds(0, 12+(4*i), 90, 18);
        }
        myPanel.add(bottone);
     }
     ......
     ......
     firstPanel.add(myPanel);

So, how can i do to insert it into a scroll?

2
  • 2
    Easy. First and foremost DON'T use a null layout. Doing this marks your code as a newbie's program since if you've created Swing GUI's for any length of time, you'll know that it's far easier to create and maintain gui's that appropriately use layout managers. But more important, use of null layouts almost guarantees that the component held by the JScrollPane won't scroll appropriately. Mar 6, 2015 at 23:06
  • Also check out this answer as a possible duplicate. Mar 6, 2015 at 23:11

1 Answer 1

4

Your question appears to ask about how to add a JPanel to a JScrollPane when the JPanel uses null layout, and the answer is easy:

  • First and foremost DON'T use a null layout. Use of null layouts almost guarantees that the component held by the JScrollPane won't scroll appropriately since the JScrollPane mechanics require the use of this.
  • Either this or you will be required to create a class that extends JPanel and implements the Scrollable interface, and this will require far more work, and completely unnecessary work.
  • Instead you really are forced to learn how to use and then use an appropriate mix of layout managers to have your JPanels hold and display their components. Note that you can nest JPanels, each using its own layout, thereby easily creating complex but easy to maintain GUI's. Please check the layout manager tutorial for more on this.
  • Adding a JPanel to a JScrollPane is easy. Either pass the JPanel into the JScrollPane's constructor: JScrollPane scrollpane = new JScrollPane(myPanel); or else pass the JPanel into the JScrollPane's viewport view via setViewportView(myPanel). Here's the JScrollPane tutorial for more on this, and the general Swing tutorials.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.