Java中的JScrollBar和JScrollPane有什么区别?

What are the differences between a JScrollBar and a JScrollPane in Java?

JScrollBar是组件,它不处理自己的事件,而JScrollPane是容器,它处理自己的事件并执行自己的滚动。 JScrollBar不能具有JScrollPane,而JScrollPane可以具有JScrollBar。

JScrollBar

  • JScrollBarclass的对象用于添加水平和垂直滚动条,允许用户在指定的最小值和最大值之间选择项目。
  • JScrollBarclass是滚动条的实现,并且继承了JComponentclass。

句法

1
public class JScrollBar extends JComponent implements Adjustable, Accessible

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import javax.swing.*;
import java.awt.*;
public class JScrollBarTest extends JFrame{
 JScrollBarTest() {
   setTitle("JScrollBar Test");
   JScrollBar jsb = new JScrollBar();
   setLayout(new FlowLayout());
   add(jsb);
   setSize(350, 275);
   setLocationRelativeTo(null);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String args[]) {
   new JScrollBarTest();
 }
}

输出量

JScrollPane

  • JSrollPaneis用于制作组件的可滚动视图。
  • 滚动窗格是JScrollPaneclass的对象,该对象扩展了JComponentclass。
  • 当屏幕大小受到限制时,我们使用滚动窗格来显示大型组件或大小可以动态更改的组件。
  • JScrollPaneclass的重要方法是setColumnHeaderView(),
    setRowHeaderView(),setViewportView()等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import javax.swing.*;
import java.awt.*;
public class JScrollPaneTest extends JFrame {
 JScrollPaneTest() {
   setTitle("JScrollPane Test");
   JPanel panel = new JPanel();
   panel.setLayout(new BorderLayout());
   JScrollPane jsp = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,     ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
   add(jsp);
   setSize(350, 275);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setLocationRelativeTo(null);
   setVisible(true);
 }
 public static void main(String[] args) {
   new JScrollPaneTest();
 }
}

输出量