java - 在 JFrame 中移动立方体时显示 X Y 坐标

标签 java swing jframe coordinates positioning

我正在学习 Java,非常感谢您的帮助。

我正在努力获得这种效果 http://tinypic.com/r/339p0ud/8

我使用堆栈溢出 'MOVE CUBE' 示例: How Do I Use KeyEventDispatcher

stack overflow '点击坐标'例子: Using the coordinate plane in the JFrame

我想把它们连在一起,这样我就有了一个立方体,我可以用我的 key 四处移动, 正如我所做的那样,坐标显示在立方体旁边(因此坐标随立方体移动)并随着位置的变化而变化。

我很想知道这是如何完成的,因为过去一周我已经尽力而为,但没有成功。

在此先感谢您提供的任何帮助或提示, 乔

MOVE.java(用键移动方 block )

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(获取 JFrame 中的 x 和 y 位置)

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);
}
}

最佳答案

不确定这是否是您想要的,我删除了坐标并在一个类中完成了所有操作

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();

        }
    });
}
}

关于java - 在 JFrame 中移动立方体时显示 X Y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23443141/

相关文章:

java - 为什么 PackageInfo.signatures 字段是一个数组,什么时候这里只有一个值?

java - 用于 AWT/Swing 的 Java JDK 1.7 中的 Apple Retina 显示支持

java - FEST:如何正确使用NoExitSecurityManager?

java - Fragment 还是 MapView?

java - 如何正确地向 sip 服务器重新注册?

java - "PKIX path building failed"和 "unable to find valid certification path to requested target"

java - Swing/JFrame 与 AWT/Frame 在 EDT 之外的渲染

Java JButton 不会遍历容器中的 JLabel(带有图像)

java - 我无法将按钮移至底部 - JFrame

java - 将控制从 JFrame 转移回调用类