Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling a JPanel

I want a JPanel with a size and defined position. Inside the JPanel, I've certain number of elements (buttons) inserted horizontally. Because my JPanel has a defined width, if I add much buttons, I couldn't see that. In this case, I need a scrollbar for this JPanel. But this JPanel must be a CERTAIN SIZE IN A CERTAIN POSITION inside a JFrame. The scrollbar of the JPanel has positioned under it horizontally. Someone can help me? I've tried it without success!

like image 507
Chu Avatar asked Apr 27 '12 07:04

Chu


People also ask

How do I make my JPanel scrollable?

The important methods of a JPanel class are getAccessibleContext(), getUI(), updateUI() and paramString(). We can also implement a JPanel with vertical and horizontal scrolls by adding the panel object to JScrollPane.

How do I add a scroll pane to a JPanel?

getContentPane(). add(scrollPanel); This code will work in general to add JScrollPane to JPanel. Adjust bounds of frame, panel and scrollpane according to your requirements but ensure that the bounds of JScrollPane are within the bounds of the frame otherwise the scrollpane will not be visible.

How do I make a scrollable Jlabel?

Place a panel in location where you want the label to be, set it's AutoScroll property to true. Then place the label in the panel, anchor it and set it's AutoSize property to true. This will make the panel provide the scroll bars if the label's text extends outside of the panel.


1 Answers

Use a JScrollPane and force its preferredSize to your given size (or set the scrollPane container LayoutManager to null and call setBounds() on the scrollpane). Also set the scrollbar policies. Here is a small sample of that:

import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Test {

    public static void main(String... args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        for (int i = 0; i < 10; i++) {
            panel.add(new JButton("Hello-" + i));
        }
        JScrollPane scrollPane = new JScrollPane(panel);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        scrollPane.setBounds(50, 30, 300, 50);
        JPanel contentPane = new JPanel(null);
        contentPane.setPreferredSize(new Dimension(500, 400));
        contentPane.add(scrollPane);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setVisible(true);
    }
}
like image 151
Guillaume Polet Avatar answered Oct 26 '22 12:10

Guillaume Polet