Pregunta

I need to create an area on which one would normally apply a scrollbar, it has to scroll horizontally (the contents is only a view into a larger logical area), but I have to use some special controls placed left and right to the control in order to scroll.

I have thougth about using absolute values (according to the logical view and subtract an offset. Thus, the controls right to the offset would be placed with negative x- values and thus discarded. Controls with x values above the width would also be discarded.

Is this a valid approach?

Best regards Soeren

¿Fue útil?

Solución

You can can create a JScrollPane over a Component (your larger logical area) and remove the scrollbars.

You can then add buttons to scroll left and right. When clicked these buttons should move the view of your scrollpane. This is done by setting the absolute position of the view. You can make this relative by first getting the absolute position of the view and then incrementing/decrementing it and setting it again.

Here's a class that shows a scrollable window of a larger image.

public class ViewScroller {

  public ViewScroller() {
    JFrame frame = new JFrame("ViewScroller");
    final ImageIcon image = new ImageIcon("path\\to\\my\\image");
    JLabel label = new JLabel(image);
    final JScrollPane scrollPane = new JScrollPane(label);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

    JButton left = new JButton("<");
    left.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        Point p = scrollPane.getViewport().getViewPosition();
        p.x = p.x < 10 ? 0 : p.x - 10;
        scrollPane.getViewport().setViewPosition(p);
      }
    });

    JButton right = new JButton(">");
    right.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        Point p = scrollPane.getViewport().getViewPosition();
        int offset = p.x + scrollPane.getViewport().getWidth();
        p.x = offset + 10 > image.getIconWidth() ? p.x : p.x + 10;
        scrollPane.getViewport().setViewPosition(p);
      }
    });

    frame.add(right, BorderLayout.EAST);
    frame.add(left, BorderLayout.WEST);
    frame.add(scrollPane, BorderLayout.CENTER);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);
  }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top