user2520969
user2520969

Reputation: 1389

Insert a JPanel with null layout into a JScroll

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?

Upvotes: 0

Views: 79

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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.

Upvotes: 4

Related Questions