How do I scroll JScrollPane viewport containing a JPanel to a specific location

Heheas picture Heheas · Oct 25, 2011 · Viewed 11.1k times · Source

I am trying to create a large game board that only part of it will be visible in the viewport and would like to be able to move the viewport around using the arrow keys to see the whole board. Right now I have a JScrollPane that contains a JPanel that will have Images and text and other stuff, but those are irrelevant. Right now I have an ImageIcon at the same size as the JPanel as a background and I would like to have an option to move the viewport around by using keys, and not have any visible scrollbars. I have tried calling getViewPort().setViewPosition() followed by revalidate() on the JPanel and the JScrollPane. But it still does not work. My code is below

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import java.awt.*;
import java.awt.event.*;


public class Game extends JPanel {

    JPanel game = new JPanel();
    JScrollPane scrollPane = new JScrollPane(game);
    JLabel grass = new JLabel();

    private KeyListener keys = new KeyListener() {
        public void keyTyped(KeyEvent e) {

        }
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                System.out.println("Down");
                scrollPane.getViewport()

            } else if (e.getKeyCode() == KeyEvent.VK_UP) {
                System.out.println("up");
            }
            revalidate();
        }
        public void keyPressed(KeyEvent e) {

        }
    };

public void createGame(int turns) {

        int gameWidth = 1800;
        int gameHeight = 1600;

        int viewPortWidth = 800;
        int viewPortHeight = 600;

        //setLayout(null);
        setSize(new Dimension(viewPortWidth, viewPortHeight));

        game.setLayout(null);
        game.setSize(new Dimension(gameWidth, gameHeight));

        //add the background image
        ImageIcon background = new ImageIcon("Grass.png");
        grass.setIcon(background);
        grass.setBounds(0,0, gameWidth, gameHeight);
        game.setBackground(Color.GREEN);
        game.add(grass);
        game.setBounds(0,0, gameWidth, gameHeight);

        //key listener
        game.addKeyListener(keys);

        //add(game);
        scrollPane.setPreferredSize(new Dimension(viewPortWidth, viewPortHeight));

        add(scrollPane);

    }


}

Answer

trashgod picture trashgod · Oct 25, 2011

There's an example that uses scrollRectToVisible() here and here. You should be able to adapt it to your usage.

As an aside, consider using key bindings, shown here, here and here.