2

I'm learning Java and would really appreciate some help.

I'm trying to get this effect http://tinypic.com/r/339p0ud/8

I using stack overflow 'MOVE CUBE' example: How Do I Use KeyEventDispatcher

and

stack overflow 'Click coordinate' example: Using the coordinate plane in the JFrame

I wish to join them together, so that I have a cube I can move around with my keys and as I do the coordinates show up next to the cube (so the coordinates move with the cube) and change as the position changes.

I would be fascinated to see how this is done as I have tried my best the past week with no success.

thanks in advance for any help or tips you provide here, Joe

MOVE.java (move the block around with keys)

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

public class Move extends JPanel {

public static final long serialVersionUID = 1L;
public static final String IMAGE_PATH = "http://mathforum.org/alejandre/magic.square/4x4grid.gif";
public static final String IMAGE_PATH_PLAYER = "http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Square-symbol.svg/50px-Square-symbol.svg.png";
public static final int STEP = 3;
public static final int TIMER_DELAY = STEP * 8;
public BufferedImage bkgrndImage = null;
public BufferedImage playerImage = null;
public Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();
public int playerX = 0;
public int playerY = 0;

enum Direction {

    UP(KeyEvent.VK_UP, 0, -1), DOWN(KeyEvent.VK_DOWN, 0, 1),
    LEFT(KeyEvent.VK_LEFT, -1, 0), RIGHT(KeyEvent.VK_RIGHT, 1, 0);
    public int keyCode;
    public int xDirection;
    public int yDirection;

    private Direction(int keyCode, int xDirection, int yDirection) {
        this.keyCode = keyCode;
        this.xDirection = xDirection;
        this.yDirection = yDirection;
    }

    public int getKeyCode() {
        return keyCode;
    }

    public int getXDirection() {
        return xDirection;
    }

    public int getYDirection() {
        return yDirection;
    }
}


public Move() {
    try {
        URL bkgrdImageURL = new URL(IMAGE_PATH);
        URL playerImageURL = new URL(IMAGE_PATH_PLAYER);
        bkgrndImage = ImageIO.read(bkgrdImageURL);
        playerImage = ImageIO.read(playerImageURL);
        setPreferredSize(new Dimension(bkgrndImage.getWidth(),          bkgrndImage.getHeight()));

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    for (Direction direction : Direction.values()) {
        directionMap.put(direction, false);
    }
    setKeyBindings();
    Timer timer = new Timer(TIMER_DELAY, new TimerListener());
    timer.start();
}




public void setKeyBindings() {
    InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actMap = getActionMap();
    for (final Direction direction : Direction.values()) {
        KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, false);
        KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, true);
        inMap.put(pressed, direction.toString() + "pressed");
        inMap.put(released, direction.toString() + "released");
        actMap.put(direction.toString() + "pressed", new AbstractAction() {

            public static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionMap.put(direction, true);
            }
        });
        actMap.put(direction.toString() + "released", new AbstractAction() {

            public static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionMap.put(direction, false);
            }
        });
    }

}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (bkgrndImage != null) {
        g.drawImage(bkgrndImage, 0, 0, null);
    }
    if (playerImage != null) {
        g.drawImage(playerImage, playerX, playerY, null);
    }
}

public class TimerListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        boolean moved = false;
        for (Direction direction : Direction.values()) {
            if (directionMap.get(direction)) {
                playerX += STEP * direction.getXDirection();
                playerY += STEP * direction.getYDirection();
                moved = true;
            }
        }
        if (moved) {
            int x = playerX - 2 * STEP;
            int y = playerY - 2 * STEP;
            int w = playerImage.getWidth() + 4 * STEP;
            int h = playerImage.getHeight() + 4 * STEP;
            Move.this.repaint(x, y, w, h); // !! repaint just the player
        }
    }
}

public static void createAndShowUI() {
    JFrame frame = new JFrame("MoveIcon");
    frame.getContentPane().add(new Move());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            createAndShowUI();
        }
    });
}

COORDINATE.java (get x and y position in JFrame)

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Coordinate
{
private int x;
private int y;
private String text;
private DrawingBase canvas;

private void displayGUI()
{
    JFrame frame = new JFrame("Drawing Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    canvas = new DrawingBase();
    canvas.addMouseListener(new MouseAdapter()
    {
        public void mouseClicked(MouseEvent me)
        {
            text = "X : " + me.getX() + " Y : " + me.getY();
            x = me.getX();
            y = me.getY();
            canvas.setValues(text, x, y);
        }
    }); 

    frame.setContentPane(canvas);
    frame.pack();
    frame.setLocationByPlatform(true);
    frame.setVisible(true);
}

public static void main(String... args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            new Coordinate().displayGUI();
        }
    });
}
}

class DrawingBase extends JPanel
{
private String clickedAt = "";
private int x = 0;
private int y = 0;

public void setValues(String text, int x, int y)
{
    clickedAt = text;
    this.x = x;
    this.y = y;
    repaint();
}

public Dimension getPreferredSize()
{
    return (new Dimension(500, 400));
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawString(clickedAt, x, y);
}
}
Community
  • 1
  • 1
JoeFlow
  • 23
  • 5
  • 1
    2 JFrame can not be added to each other. How exactly do you want Coordinate to be showed? – phil652 May 03 '14 at 16:18
  • yes that is right ...what I was trying previously with no success, was to paint the box to JPanel and paint the coordinates onto another overlapping JPanel and align the two together... – JoeFlow May 03 '14 at 17:06
  • Do you want the coordinate to be showed on the same frame or on another frame? – phil652 May 03 '14 at 17:08
  • same frame ...and to move in time with the box move ...i tried to get the coordinates to be placed in the top right corner of the box. – JoeFlow May 03 '14 at 17:12
  • Apologies ...I tried to post an image of what I'm trying to do, but do not have 10+ reputation yet ...here is a link: http://tinypic.com/r/339p0ud/8 – JoeFlow May 03 '14 at 17:26
  • Make Coordinate an Object instead of a JFrame and add it to your JFrame doing Coordinate c = new Coordinate(); – phil652 May 03 '14 at 17:33
  • Thanks Phil ...but that's the part I'm stuck on ...tying the two together. Also I would like a little placement control when it comes to positioning the coordinates around the cube. ...please share any example code you have. thanks in advance. J – JoeFlow May 03 '14 at 17:47

2 Answers2

0
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (bkgrndImage != null) {
        g.drawImage(bkgrndImage, 0, 0, null);
    }
    if (playerImage != null) {
        g.drawImage(playerImage, playerX, playerY, null);
        //offsetX and offsetY are the location relative to the cube to draw the string
        //also note that the y coordinate is the location where the BOTTOM of the string begins
        g.drawString("Clicked at: " + playerX + "," + playerY + ".", playerX + offsetX, playerY + offsetY)
    }
}

This will draw to the location of the player. I can't imagine that it requires much effort to adjust it to draw to the clicked position.

Aarowaim
  • 801
  • 4
  • 10
  • thanks, I get strange behavior in the the positioning of the coordinates now when moving about :) ...any idea how I can pin the coordinates to the cube ...I can resolve the trails left behind later... – JoeFlow May 03 '14 at 18:47
  • when I add... playerX + xPosition, playerY + yPosition); I seem to lose coordinates halfway off the screen? ...the coordinates are pinned to the cube though :) – JoeFlow May 03 '14 at 18:53
  • all working now :) thanks Phil! really appreciated! BIG help! :D – JoeFlow May 03 '14 at 18:56
0

No sure if this is what you want, I removed Coordinate and did everything in one class

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.awt.image.TileObserver;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;

import org.w3c.dom.events.EventTarget;
import org.w3c.dom.events.MouseEvent;
import org.w3c.dom.views.AbstractView;

public class Move extends JPanel{

public static final long serialVersionUID = 1L;
public static final String IMAGE_PATH = "http://mathforum.org/alejandre/magic.square/4x4grid.gif";
public static final String IMAGE_PATH_PLAYER = "http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Square-symbol.svg/50px-Square-symbol.svg.png";
public static final int STEP = 3;
public static final int TIMER_DELAY = STEP * 8;
public BufferedImage bkgrndImage = null;
public BufferedImage playerImage = null;
public Map<Direction, Boolean> directionMap = new HashMap<Direction, Boolean>();
public int playerX = 0;
public int playerY = 0;
private static int xPosition = 0;
private static int yPosition = 0;
private String s = "";
private JLabel jlbl1 = new JLabel("");
enum Direction {

    UP(KeyEvent.VK_UP, 0, -1), DOWN(KeyEvent.VK_DOWN, 0, 1),
    LEFT(KeyEvent.VK_LEFT, -1, 0), RIGHT(KeyEvent.VK_RIGHT, 1, 0);
    public int keyCode;
    public int xDirection;
    public int yDirection;

    private Direction(int keyCode, int xDirection, int yDirection) {
        this.keyCode = keyCode;
        this.xDirection = xDirection;
        this.yDirection = yDirection;
    }

    public int getKeyCode() {
        return keyCode;
    }

    public int getXDirection() {
        return xDirection;
    }

    public int getYDirection() {
        return yDirection;
    }

}
public Move() {

    this.add(jlbl1,new Dimension(100,100));
    try {
        URL bkgrdImageURL = new URL(IMAGE_PATH);
        URL playerImageURL = new URL(IMAGE_PATH_PLAYER);
        bkgrndImage = ImageIO.read(bkgrdImageURL);
        playerImage = ImageIO.read(playerImageURL);
        setPreferredSize(new Dimension(bkgrndImage.getWidth(),          bkgrndImage.getHeight()));

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    for (Direction direction : Direction.values()) {
        directionMap.put(direction, false);
    }
    setKeyBindings();
    Timer timer = new Timer(TIMER_DELAY, new TimerListener());
    timer.start();

}

public void setKeyBindings() {
    InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actMap = getActionMap();
    for (final Direction direction : Direction.values()) {
        KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, false);
        KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, true);
        inMap.put(pressed, direction.toString() + "pressed");
        inMap.put(released, direction.toString() + "released");
        actMap.put(direction.toString() + "pressed", new AbstractAction() {

            public static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionMap.put(direction, true);
            }
        });
        actMap.put(direction.toString() + "released", new AbstractAction() {

            public static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionMap.put(direction, false);
            }
        });
    }

}
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (bkgrndImage != null) {
        g.drawImage(bkgrndImage, 0, 0, null);
    }
    if (playerImage != null) {
        g.drawImage(playerImage, playerX, playerY, null);
    }
}

public class TimerListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        boolean moved = false;
        for (Direction direction : Direction.values()) {
            if (directionMap.get(direction)) {
                playerX += STEP * direction.getXDirection();
                playerY += STEP * direction.getYDirection();


                moved = true;
            }
        }
        if (moved) {
            int x = playerX - 2 * STEP;
            int y = playerY - 2 * STEP;
            int w = playerImage.getWidth() + 4 * STEP;
            int h = playerImage.getHeight() + 4 * STEP;
            Move.this.repaint(x, y, w, h); // !! repaint just the player
        }
        s = playerX+", "+playerY;
        jlbl1.setText(s);


    }
}

public static void createAndShowUI() {
    JFrame frame = new JFrame("MoveIcon");
    frame.getContentPane().add(new Move());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            createAndShowUI();

        }
    });
}
}
phil652
  • 1,484
  • 1
  • 23
  • 48
  • Excellent Phil ...I'm smiling right now, thanks ...but I'm still playing around with drawing the coordinates to the cube as it move, I'm playing around with your previous 'paintComponent' solution ...any more ideas on Painting the coordinates with the cube? rather than at top center of the JFrame? – JoeFlow May 03 '14 at 18:32
  • Look at Aarowaim solution, the coordinates are with the cube but there is a few bugs. Try mixing both answer and this might work – phil652 May 03 '14 at 18:34