杰瑞科技汇

java jscrollpane

Of course! Let's dive deep into JScrollPane in Java Swing. It's one of the most fundamental and commonly used components.

java jscrollpane-图1
(图片来源网络,侵删)

What is a JScrollPane?

A JScrollPane is a specialized container that provides a viewport (a "window" onto a larger area) with optional scrollbars and row/column headers. Its primary purpose is to make a component that is too large to fit in a small space scrollable.

Think of it like this: you have a huge poster (JComponent) but only a small picture frame (JPanel). You can't fit the whole poster in the frame. A JScrollPane is like a special picture frame that has little handles (scrollbars) on the side and bottom. You can use these handles to slide the poster around to see different parts of it.


Key Concepts of a JScrollPane

To use JScrollPane effectively, you need to understand its main parts:

  1. Viewport (JViewport): This is the most important part. It's a transparent window that shows a small portion of the main component. The JScrollPane manages the viewport's position. You almost never interact with the viewport directly; you just tell the JScrollPane what component to put inside it.

    java jscrollpane-图2
    (图片来源网络,侵删)
  2. Scrollbars (JScrollBar): These are the familiar vertical and horizontal bars with sliders. JScrollPane automatically decides whether to show them based on the size of the component inside versus the size of the viewport. You can control this behavior.

  3. Corner Component: The space where the vertical and horizontal scrollbars meet. You can place a component here, like a small button or a label.

  4. Row and Column Headers: Optional components that appear next to the scrollbars. They are often used with tables (JTable) to show headers like "A, B, C..." for columns or "1, 2, 3..." for rows.


How to Use JScrollPane: The Basic Steps

Using a JScrollPane is a three-step process:

java jscrollpane-图3
(图片来源网络,侵删)
  1. Create the component you want to make scrollable. This could be a JTextArea, a JPanel with many components, a JTable, a JList, etc.
  2. Create a JScrollPane, passing your component to its constructor.
  3. Add the JScrollPane to your main container (e.g., a JFrame or JPanel), not the original component.

Example 1: Scrolling a JTextArea

This is the classic example. A JTextArea is perfect for displaying large amounts of text.

import javax.swing.*;
import java.awt.*;
public class JScrollPaneExample {
    public static void main(String[] args) {
        // 1. Create the main frame
        JFrame frame = new JFrame("JScrollPane Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);
        frame.setLayout(new BorderLayout());
        // 2. Create the component to be scrolled (a JTextArea)
        JTextArea textArea = new JTextArea(20, 30); // 20 rows, 30 columns
        textArea.setText("This is a JTextArea.\n\n");
        for (int i = 0; i < 100; i++) {
            textArea.append("Line " + (i + 1) + " of some very long text that will not fit in the visible area.\n");
        }
        // 3. Create the JScrollPane, passing the JTextArea to it
        JScrollPane scrollPane = new JScrollPane(textArea);
        // 4. Add the JScrollPane to the frame
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.setVisible(true);
    }
}

Explanation:

  • We create a JTextArea and fill it with more text than can fit in its default size.
  • We create a JScrollPane and immediately pass the textArea to its constructor. This tells the scroll pane to manage the textArea.
  • We add the scrollPane itself to the frame. The JScrollPane is now responsible for displaying the textArea and providing scrollbars when needed.

Advanced Customization

The JScrollPane constructor is convenient, but you often need more control. You can create the JScrollPane empty and then configure it.

Example 2: Customizing Scrollbar Policies

What if you always want to see a scrollbar, or never want to see one? You can control this with setVerticalScrollBarPolicy() and setHorizontalScrollBarPolicy().

The policies are constants from the JScrollPane class:

  • JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED (Default)
  • JScrollPane.VERTICAL_SCROLLBAR_NEVER
  • JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
  • JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED (Default)
  • JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
  • JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
import javax.swing.*;
import java.awt.*;
public class ScrollPolicyExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Custom Scroll Policies");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new GridLayout(2, 1, 5, 5)); // 2 rows, 1 column
        // --- Example 1: Always show vertical scrollbar ---
        JTextArea textArea1 = new JTextArea(10, 20);
        textArea1.setText("This pane will always show a vertical scrollbar,\n");
        textArea1.append("even if the content is small.\n\n");
        textArea1.append("Short content.");
        JScrollPane scrollPane1 = new JScrollPane(textArea1);
        scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        // --- Example 2: Never show horizontal scrollbar ---
        JTextArea textArea2 = new JTextArea(5, 50); // Very wide
        textArea2.setText("This pane will never show a horizontal scrollbar.\n");
        textArea2.append("You will have to use the vertical scrollbar to see the rest of this very wide line: ");
        for (int i = 0; i < 20; i++) {
            textArea2.append("This is part of the long line. ");
        }
        JScrollPane scrollPane2 = new JScrollPane(textArea2);
        scrollPane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        frame.add(scrollPane1);
        frame.add(scrollPane2);
        frame.pack(); // Sizes the frame to fit its components
        frame.setVisible(true);
    }
}

Example 3: Scrolling a Custom JPanel

You can put any JComponent inside a JScrollPane. This is extremely useful for creating complex UIs, like a map editor, a large form, or a custom dashboard.

import javax.swing.*;
import java.awt.*;
public class ScrollablePanelExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Scrollable JPanel");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        // 1. Create a large custom JPanel
        JPanel largePanel = new JPanel();
        largePanel.setLayout(new GridLayout(20, 5, 10, 10)); // 20 rows, 5 columns of buttons
        largePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        for (int i = 0; i < 100; i++) { // 20 * 5 = 100 buttons
            JButton button = new JButton("Button " + (i + 1));
            largePanel.add(button);
        }
        // 2. Create a JScrollPane to hold the large panel
        JScrollPane scrollPane = new JScrollPane(largePanel);
        // 3. Add the scroll pane to the frame
        frame.add(scrollPane);
        frame.setVisible(true);
    }
}

Best Practices and Tips

  1. Always add the JScrollPane to your container, not the component inside it. This is the most common mistake for beginners. The JScrollPane provides the borders and scrollbars.

  2. Use the Right Constructor: For simple cases, new JScrollPane(myComponent) is fine. For more complex setups (e.g., adding headers), create the JScrollPane first and then use setViewportView().

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(myComponent); // Alternative to the constructor
  3. Set Preferred Size: If the component inside the scroll pane has no preferred size (like an empty JPanel), the scroll pane might not show scrollbars correctly. Always set a preferred size on the component you're adding.

    myPanel.setPreferredSize(new Dimension(800, 600));
    JScrollPane scrollPane = new JScrollPane(myPanel);
  4. JScrollPane vs. JViewport: You will almost always use JScrollPane. JViewport is a lower-level class. JScrollPane is a convenience class that bundles a JViewport with two JScrollBars and provides all the common scrollbar policy logic for you.

分享:
扫描分享到社交APP
上一篇
下一篇