Java Tutorial/Swing/JScrollPane

Материал из Java эксперт
Версия от 15:34, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A corner component is displayed only if the two components at a right angle from the corner are currently shown.

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JScrollPaneHeadersandCorners {
  public static void main(String args[]) {
    final Object rows[][] = { { "one", "1" }, { "two", "2" }, { "three", "3" }, { "four", "4" },
    };
    final Object headers[] = { "English", "#" };
    JFrame frame = new JFrame("Table Printing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JTable table = new JTable(rows, headers);
    JScrollPane scrollPane = new JScrollPane(table);
    frame.add(scrollPane, BorderLayout.CENTER);
    scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, new JButton("..."));
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





Add component to JScrollPane

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
public class AddingToJScrollPane {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel("Label");
    label.setPreferredSize(new Dimension(1000, 1000));
    JScrollPane jScrollPane = new JScrollPane(label);
    JButton jButton1 = new JButton();
    jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane.setViewportBorder(new LineBorder(Color.RED));
    jScrollPane.getViewport().add(jButton1, null);
    frame.add(jScrollPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}





Adding component to JScrollPane using its constructor

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class AddingToJScrollPane {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel("Label");
    label.setPreferredSize(new Dimension(1000, 1000));
    JScrollPane jScrollPane = new JScrollPane(label);
    frame.add(jScrollPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}





Create a scrollable list

import javax.swing.JList;
import javax.swing.JScrollPane;
public class Main {
  public static void main(String[] argv) throws Exception {
    JList list = new JList();
    JScrollPane scrollableList = new JScrollPane(list);
  }
}





Customizing a JScrollPane Look and Feel

Property StringObject TypeScrollPane.actionMapActionMapScrollPane.ancestorInputMapInputMapScrollPane.ancestorInputMap.RightToLeftInputMapScrollPane.backgroundColorScrollPane.borderBorderScrollPane.fontFontScrollPane.foregroundColorScrollPane.viewportBorderBorderScrollPane.viewportBorderInsetsInsetsScrollPaneUIString


Get the default scrollbar policy

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    // Get the default scrollbar policy
    int hpolicy = pane.getHorizontalScrollBarPolicy();
    // JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    int vpolicy = pane.getVerticalScrollBarPolicy();
    // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;
  }
}





JScrollPane: display a large component within a smaller display area

Adding the component to a JViewport

Identifying the component to be scrolled can be done in one of two ways.



import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
public class JScrollPaneViewport {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JLabel label = new JLabel("Label");
    label.setPreferredSize(new Dimension(1000,1000));
    JScrollPane jScrollPane = new JScrollPane();
    jScrollPane.setViewportView(label);
    frame.add(jScrollPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}





JScrollPane Scrollbar Policies

Policy TypeDescriptionVERTICAL_SCROLLBAR_AS_NEEDEDDisplays designated scrollbar if viewport is too small to display its entire contentsHORIZONTAL_SCROLLBAR_AS_NEEDEDDisplays designated scrollbar if viewport is too small to display its entire contentsVERTICAL_SCROLLBAR_ALWAYSAlways displays designated scrollbarHORIZONTAL_SCROLLBAR_ALWAYSAlways displays designated scrollbarVERTICAL_SCROLLBAR_NEVERNever displays designated scrollbarHORIZONTAL_SCROLLBAR_NEVERNever displays designated scrollbar


Listening for Scrollbar Value Changes in a JScrollPane Container

import java.awt.Adjustable;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    // Listen for value changes in the scroll pane"s scrollbars
    AdjustmentListener listener = new MyAdjustmentListener();
    pane.getHorizontalScrollBar().addAdjustmentListener(listener);
    pane.getVerticalScrollBar().addAdjustmentListener(listener);
  }
}
class MyAdjustmentListener implements AdjustmentListener {
  public void adjustmentValueChanged(AdjustmentEvent evt) {
    Adjustable source = evt.getAdjustable();
    if (evt.getValueIsAdjusting()) {
      return;
    }
    int orient = source.getOrientation();
    if (orient == Adjustable.HORIZONTAL) {
      System.out.println("from horizontal scrollbar"); 
    } else {
      System.out.println("from vertical scrollbar");
    }
    int type = evt.getAdjustmentType();
    switch (type) {
    case AdjustmentEvent.UNIT_INCREMENT:
      System.out.println("Scrollbar was increased by one unit");
      break;
    case AdjustmentEvent.UNIT_DECREMENT:
      System.out.println("Scrollbar was decreased by one unit");
      break;
    case AdjustmentEvent.BLOCK_INCREMENT:
      System.out.println("Scrollbar was increased by one block");
      break;
    case AdjustmentEvent.BLOCK_DECREMENT:
      System.out.println("Scrollbar was decreased by one block");
      break;
    case AdjustmentEvent.TRACK:
      System.out.println("The knob on the scrollbar was dragged");
      break;
    }
    int value = evt.getValue();
  }
}





Make the scrollbars always appear

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
  }
}





Make the scrollbars never appear

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea();
    JScrollPane pane = new JScrollPane(textArea);
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
  }
}





Resetting the Viewport Position: move JScrollPane to the top

import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
class JScrollPaneToTopAction implements ActionListener {
  JScrollPane scrollPane;
  public JScrollPaneToTopAction(JScrollPane scrollPane) {
    if (scrollPane == null) {
      throw new IllegalArgumentException(
        "JScrollPaneToTopAction: null JScrollPane");
    }
    this.scrollPane = scrollPane;
  }
  public void actionPerformed(ActionEvent actionEvent) {
    JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
    JScrollBar horizontalScrollBar = scrollPane.getHorizontalScrollBar();
    verticalScrollBar.setValue(verticalScrollBar.getMinimum());
    horizontalScrollBar.setValue(horizontalScrollBar.getMinimum());
  }
}

public class JScrollPaneToTopActionDemo {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel label = new JLabel("Label");
    label.setPreferredSize(new Dimension(1000, 1000));
    JScrollPane jScrollPane = new JScrollPane(label);
    JButton bn = new JButton("Move");
    
    bn.addActionListener(new JScrollPaneToTopAction(jScrollPane));
    
    frame.add(bn, BorderLayout.SOUTH);
    frame.add(jScrollPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}





Set Continuous Layout

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class Test extends JFrame {
  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel1 = new JPanel(new GridLayout(1, 5));
    for (int i = 0; i < 5; i++) {
      panel1.add(new JLabel("Left " + i));
    }
    panel1.setPreferredSize(new Dimension(250, 50));
    JPanel panel2 = new JPanel(new GridLayout(1, 5));
    for (int i = 0; i < 5; i++) {
      panel2.add(new JLabel("Right " + i));
    }
    panel2.setPreferredSize(new Dimension(250, 50));
    final JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
        panel1, panel2);
    split.setContinuousLayout(true);
    getContentPane().add(split, BorderLayout.CENTER);
    pack();
    setSize(500, 100);
  }
  public static void main(String[] args) {
    new Test().setVisible(true);
  }
}





Set Row Header View

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JScrollPaneRowHeaderView extends JFrame {
  public JScrollPaneRowHeaderView() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new GridLayout(5, 10));
    for (int i = 0; i < 50; i++) {
      panel.add(new JLabel("  Label " + i));
    }
    JScrollPane scrolled = new JScrollPane(panel);
    scrolled.setRowHeaderView(new JLabel("Labels: "));
    getContentPane().add(scrolled, BorderLayout.CENTER);
    pack();
    setSize(300, 100);
    setVisible(true);
  }
  public static void main(String[] args) {
    new JScrollPaneRowHeaderView();
  }
}





Working with JScrollPane Headers and Corners

To place a component in one of the corners of the JScrollPane, call setCorner(String key, Component corner) key is

  1. JScrollPane.LOWER_LEFT_CORNER,
  2. JScrollPane.LOWER_RIGHT_CORNER,
  3. JScrollPane.UPPER_LEFT_CORNER, or
  4. JScrollPane.UPPER_RIGHT_CORNER.



import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
public class MainClass {
  public static void main(String[] a) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new JScrollPaneDemo());
    f.setSize(500, 500);
    f.setVisible(true);
  }
}
class JScrollPaneDemo extends JPanel {
  public void init() {
    try {
      SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
          makeGUI();
        }
      });
    } catch (Exception exc) {
      System.out.println("Can"t create because of " + exc);
    }
  }
  private void makeGUI() {
    setLayout(new BorderLayout());
    JPanel jp = new JPanel();
    jp.setLayout(new GridLayout(20, 20));
    int b = 0;
    for (int i = 0; i < 20; i++) {
      for (int j = 0; j < 20; j++) {
        jp.add(new JButton("Button " + b));
        ++b;
      }
    }
    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    JScrollPane jsp = new JScrollPane(jp, v, h);
    add(jsp, BorderLayout.CENTER);
  }
}