Working with Swing Panels: JPanel and JScrollPane
Panels in Swing function as containers that can hold other components, but they themselves must be placed within other containers.
Swing provides several panel types, with JPanel and JScrollPane being the most frequently used.
JPanel Panel
JPanel is a lightweight container that supports various layout managers. Multiple JPanel instances can be nested to create complex user interfaces.
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PanelLayoutDemo extends JFrame {
private static final long serialVersionUID = 1L;
public PanelLayoutDemo() {
Container root = getContentPane();
root.setLayout(new GridLayout(2, 1, 10, 10));
JPanel topRow = new JPanel(new GridLayout(1, 3, 10, 10));
JPanel bottomLeft = new JPanel(new GridLayout(1, 2, 10, 10));
JPanel bottomRight = new JPanel(new GridLayout(1, 2, 10, 10));
JPanel bottomSection = new JPanel(new GridLayout(2, 1, 10, 10));
topRow.add(new JButton("A"));
topRow.add(new JButton("B"));
topRow.add(new JButton("C"));
topRow.add(new JButton("D"));
bottomLeft.add(new JButton("E"));
bottomLeft.add(new JButton("F"));
bottomRight.add(new JButton("G"));
bottomRight.add(new JButton("H"));
bottomSection.add(bottomLeft);
bottomSection.add(bottomRight);
root.add(topRow);
root.add(bottomSection);
setTitle("Nested Panel Layout Example");
setSize(420, 200);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new PanelLayoutDemo();
}
}
This example demonstrates creating four JPanel instances arranged in a grid layout. Each nested panel uses its own layout manager, allowing for flexible interface design.
JScrollPane Panel
When the content exceeds the visible area of a container, JScrollPane prvoides automatic scroll bars. Unlike regular containers, JScrollPane can only hold a single component and does not allow layout managers.
To display multiple components within a JScrollPane, first arrange them on a JPanel, then add that panel to the scroll pane.
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ScrollableTextDemo extends JFrame {
private static final long serialVersionUID = 1L;
public ScrollableTextDemo() {
Container content = getContentPane();
JTextArea textArea = new JTextArea(20, 50);
JScrollPane scrollPane = new JScrollPane(textArea);
content.add(scrollPane);
setTitle("Text Editor with Scroll Bars");
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public static void main(String[] args) {
new ScrollableTextDemo();
}
}
The JTextArea component is wrapped in a JScrollPane, which automatically provides horizontal and vertical scroll bars when the text exceeds the visible bounds.