Skip to content

Tag: game

Java key listening example

This post continues a serie of posts I’m writing about 2D game development in Java.
A simple example of an JPanel that implements KeyListener (and a little trick) to handle KeyEvents to move a white square.

Java KeyListening Example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class KeyPanel extends JPanel implements KeyListener{
    private int x=50,y=50;
    public KeyPanel() {
        JTextField textfield = new JTextField();
        textfield.setPreferredSize(new Dimension(0,0));
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_LEFT)
        if (e.getKeyCode() == KeyEvent.VK_RIGHT)
        if (e.getKeyCode() == KeyEvent.VK_DOWN)
        if (e.getKeyCode() == KeyEvent.VK_UP)
    public void paintComponent(Graphics g) {
        g.fillRect(0, 0, 500, 500);
        g.fillRect(x, y, 50, 50);

Download the complete NetBeans source project files: KeyTest.tar.bz2.

JavaFX: Side-scrolling

An side-scrolling game attempt.

an plane

I used two images, this mountain background made with Gimp (xcf sources here) and that ship above made with Inkscape (svg sources here).

import javafx.ui.*;
import javafx.ui.canvas.*;
var scroll;
scroll = [1..800] dur 60000 linear continue if true;
var mountains = Clip{
    transform: bind translate(-scroll,0)
    shape: Rect {x:bind scroll, y:0, width:400, height:200}
    content: [ImageView {
            transform: translate(0,0)
            image: Image { url: ""}
        ImageView {
            transform: translate(800,0)
            image: Image { url: ""}
var h = 50;
var ship = ImageView {
    cursor: HAND
    transform: bind translate(0,h)
    image: Image { url: ""}
    onMouseDragged: operation(e) {
        h += e.localDragTranslation.y;
Canvas {
    content: [mountains, ship]