How can we implement a scrollable JPanel in Java?



JPanel

  • A JPanel is a subclass of JComponent (a subclass of a Container class). Therefore, JPanel is also a Container.
  • A JPanel is an empty area that can be used either to layout other components including other panels.
  • In a JPanel, we can add fields, labels, buttons, checkboxes, and images also.
  • The Layout Managers such as FlowLayout, GridLayout, BorderLayout and other layout managers helps us to control the sizes, positions, and alignment of the components using JPanel.
  • 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.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JScrollablePanelTest extends JFrame {
   public JScrollablePanelTest() {
      setTitle("JScrollablePanel Test");
      setLayout(new BorderLayout());
      JPanel panel = createPanel();
      add(BorderLayout.CENTER, new JScrollPane(panel));
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static JPanel createPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(10, 4, 10, 10));
      for (int i=0; i < 10; i++) {
         for (int j=0; j < 4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Arial", Font.PLAIN, 20));
            panel.add(label);
         }
      }
      return panel;
   }
   public static void main(String [] args) {
      new JScrollablePanelTest();
   }
}

Output


Advertisements