4 Replies - 1438 Views - Last Post: 06 March 2012 - 07:59 PM Rate Topic: -----

#1 wrightm96  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 51
  • Joined: 06-March 12

How to Scroll with Arrow Keys

Posted 06 March 2012 - 05:05 PM

I recently read the thread here: http://www.dreaminco...a-tile-mapping/

I realized this method was exactly what I needed, so I used the code provided in it. I modified the code according to Guest_Terrey*'s post so that it would be easier to handle.

How would I add a KeyListener that would use KeyEvents from the arrow keys to move around the screen?

import javax.swing.JFrame;

public class Main
{
	private JFrame frame;
	
	public Main()
	{
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(300, 300);
        frame.setTitle("RPG");
        frame.setResizable(false);
        
        //JScrollPane jsp = new JScrollPane(new Board());
        //jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        
		//frame.add(jsp);
        frame.add(new Board());
        frame.setVisible(true);
	}
	
	public static void main(String[] args)
	{
		new Main();
	}
}


import java.awt.Graphics;

import javax.swing.JPanel;

public class Board extends JPanel
{
	TileMap map = new TileMap();
	
	public Board()
	{
		
	}
	
	public void paintComponent(Graphics g)
	{
		int count = 0;
		
		for(int i = 0; i < map.getWidth(); i++)
		{
			for (int k = 0; k < map.getWidth(); k++)
			{
				//g.drawImage(map.getTileSet().getTileTypeAtIndex(map.getTiles()[count]).getImage(), gpft(k), gpft(i), this);
				
				//this just randomly generates some either water or grass tiles
				double rand = Math.random();
				if (rand < 0.25)
				{
					g.drawImage(map.getTileSet().getTileTypes()[0].getImage(), gpft(k), gpft(i), this);
				}
				else if (rand < 0.5)
				{
					g.drawImage(map.getTileSet().getTileTypes()[3].getImage(), gpft(k), gpft(i), this);
				}
				else if (rand < 0.75)
				{
					g.drawImage(map.getTileSet().getTileTypes()[2].getImage(), gpft(k), gpft(i), this);
				}
				else
				{
					g.drawImage(map.getTileSet().getTileTypes()[1].getImage(), gpft(k), gpft(i), this);
				}
				
				count++;
			}
		}
	}

	public int gpft(int t)//calculates the location to draw each tile image
	{
		return t * 32;//the tile images are 32 pixels by 32 pixels
	}
}


public class TileMap
{
	private TileSet tileSet;
	private int[] tiles = new int[]{0, 1, 2, 3, 0, 1, 3, 2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 1, 0, 0, 2, 2, 0};
	private int width;
	
    public TileMap()
    {
    	tileSet = new TileSet();
    	//width = (int)Math.sqrt(tiles.length);
    	width = 25;
    }
    
    public TileSet getTileSet()
    {
    	return tileSet;
    }
    
    public int[] getTiles()
    {
    	return tiles;
    }
    
    public int getWidth()
    {
    	return width;
    }
}


import java.awt.Toolkit;

public class TileSet
{
	private Tile[] tileTypes = new Tile[4];
	
	public TileSet()
	{
		init();
	}
	
	public void init()
	{
		tileTypes[0] = new Tile(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("grass.png")), "Grass");
		tileTypes[1] = new Tile(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("monster_grass.png")), "Monster Grass");
		tileTypes[2] = new Tile(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("sand_brick_path.png")), "Brick Path");
		tileTypes[3] = new Tile(Toolkit.getDefaultToolkit().getImage(getClass().getClassLoader().getResource("water.png")), "Water");
	}
	
	public Tile getTileTypeAtIndex(int index)
	{
		return tileTypes[index];
	}
	
	public Tile[] getTileTypes()
	{
		return tileTypes;
	}
}


import java.awt.Image;

public class Tile
{
	private Image image;
	private String name;
	
	public Tile(Image i, String n)
	{
		image = i;
		name = n;
	}
	
	public void setImage(Image i)
	{
		image = i;
	}
	
	public void setName(String n)
	{
		name = n;
	}
	
	public Image getImage()
	{
		return image;
	}
	
	public String getName()
	{
		return name;
	}
}

Attached image(s)

  • Attached Image
  • Attached Image
  • Attached Image
  • Attached Image


Is This A Good Question/Topic? 0
  • +

Replies To: How to Scroll with Arrow Keys

#2 NantucketSleighride  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 108
  • Joined: 13-February 11

Re: How to Scroll with Arrow Keys

Posted 06 March 2012 - 05:24 PM

I would make your main class extend a JFrame - then you have to implement a KeyListener and its methods.

So instead of making your Main class - and you've shown - simply add a JFrame, make it actually extend JFrame, thus becoming a JFrame type object itself.

import java.awt.event.*; //for the KeyListener
import javax.swing.*;

public class Main extends JFrame, implements KeyListener{

//constructor for the JFrame
public Main(){ 
//code for the frame
this.addKeyListener(this); //adds the keylistener, which happens to be the JFrame itself.
//code for the frame
}

public void keyPressed(KeyEvent e){
//what to do when key is pressed down
}

public void keyReleased(KeyEvent e){
//what to do when a key is released
}

public void keyTyped(KeyEvent e){
//what to do if it's typed (I think that means pushed down and released. Not entirely sure.
}

}




You have to have those three methods to have a KeyListener. Always.

Then you can use e.getKeyChar() to figure out what keys were pressed. What I like to do is use a System.out.println there to print out the key to the console - then you can see what the computer sees when its reading a key.

This post has been edited by NantucketSleighride: 06 March 2012 - 05:26 PM

Was This Post Helpful? 0
  • +
  • -

#3 wrightm96  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 51
  • Joined: 06-March 12

Re: How to Scroll with Arrow Keys

Posted 06 March 2012 - 05:30 PM

Thanks for the quick reply. I did what you stated, but the nothing prints.

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;

public class Main extends JFrame implements KeyListener
{
	public Main()
	{
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 300);
        setTitle("RPG");
        setResizable(false);
        add(new Board());
        setVisible(true);
	}
	
	public static void main(String[] args)
	{
		new Main();
	}

	@Override
	public void keyPressed(KeyEvent arg0)
	{
		System.out.println(arg0.getKeyChar());
	}

	@Override
	public void keyReleased(KeyEvent arg0)
	{
		System.out.println(arg0.getKeyChar());
	}

	@Override
	public void keyTyped(KeyEvent arg0)
	{
		System.out.println(arg0.getKeyChar());
	}
}


Was This Post Helpful? 0
  • +
  • -

#4 NantucketSleighride  Icon User is offline

  • D.I.C Head

Reputation: 22
  • View blog
  • Posts: 108
  • Joined: 13-February 11

Re: How to Scroll with Arrow Keys

Posted 06 March 2012 - 05:32 PM

You forgot to add the KeyListener.

this.addKeyListener(this);
Was This Post Helpful? 1
  • +
  • -

#5 wrightm96  Icon User is offline

  • D.I.C Head

Reputation: 6
  • View blog
  • Posts: 51
  • Joined: 06-March 12

Re: How to Scroll with Arrow Keys

Posted 06 March 2012 - 07:59 PM

Okay. I did that, but now it is not repainting as it should.

import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class Main extends JFrame implements KeyListener
{
	final int WIDTH = 361;
	final int HEIGHT = 383;
	Board board;
	JScrollPane jsp;
	Rectangle view;
	
	public Main()
	{
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(WIDTH, HEIGHT);
        setTitle("RPG");
        setResizable(false);
        
        board = new Board();
        jsp = new JScrollPane(board);
        
        view = new Rectangle(WIDTH, HEIGHT);
        jsp.scrollRectToVisible(view);
        
        add(jsp);
        addKeyListener(this);
        setVisible(true);
	}
	
	public static void main(String[] args)
	{
		new Main();
	}

	@Override
	public void keyPressed(KeyEvent e)
	{
		int keyCode = e.getKeyCode();
		
	    switch(keyCode)
	    { 
	        case KeyEvent.VK_UP:
	        	if (view.x > 0)
				{
	        		System.out.println("Up");
	        		view.x -= 32;
					view.setLocation(view.x, view.y);
					jsp.scrollRectToVisible(view);
					repaint();
				}
	            break;
	        case KeyEvent.VK_DOWN:
				if (view.x < board.getTileMap().getWidth() * 32)
				{
					System.out.println("Down");
					view.x += 32;
					view.setLocation(view.x, view.y);
					jsp.scrollRectToVisible(view);
					repaint();
				}
	            break;
	        case KeyEvent.VK_LEFT:
	        	if (view.y > 0)
				{
	        		System.out.println("Left");
	        		view.y -= 32;
					view.setLocation(view.x, view.y - 32);
					jsp.scrollRectToVisible(view);
					repaint();
				}
	            break;
	        case KeyEvent.VK_RIGHT :
	        	if (view.y < board.getTileMap().getWidth() * 32)
				{
	        		System.out.println("Right");
	        		view.y += 32;
					view.setLocation(view.x, view.y + 32);
					jsp.scrollRectToVisible(view);
					repaint();
				}
	        	break;
	    }
	}

	@Override
	public void keyReleased(KeyEvent e)
	{
		
	}

	@Override
	public void keyTyped(KeyEvent e)
	{
		
	}
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1