【问题标题】:Display X Y coordinates whilst moving Cube in JFrame在 JFrame 中移动 Cube 时显示 X Y 坐标
【发布时间】:2014-05-04 02:26:55
【问题描述】:

我正在学习 Java,非常感谢一些帮助。

我正在努力达到这个效果http://tinypic.com/r/339p0ud/8

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

堆栈溢出'点击坐标'示例: Using the coordinate plane in the JFrame

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

我很想看看这是如何做到的,因为过去一周我已经尽了最大努力,但没有成功。

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

MOVE.java(用键移动方块)

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

【问题讨论】:

  • 2个JFrame不能相互添加。您究竟希望如何显示坐标?
  • 是的,这是正确的......我之前尝试过的尝试没有成功,是将框绘制到 JPanel 并将坐标绘制到另一个重叠的 JPanel 上并将两者对齐......
  • 您希望坐标显示在同一帧还是另一帧?
  • 同一帧...并随着框的移动及时移动...我试图将坐标放置在框的右上角。
  • 道歉 ...我试图发布我正在尝试做的事情的图片,但还没有 10+ 的声誉...这里有一个链接:tinypic.com/r/339p0ud/8

标签: java swing jframe coordinates positioning


【解决方案1】:

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

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

        }
    });
}
}

【讨论】:

  • 优秀的菲尔......我现在正在微笑,谢谢......但我仍在玩弄在移动时绘制立方体的坐标,我在玩你以前的'paintComponent' 解决方案......关于用立方体绘制坐标的更多想法?而不是在 JFrame 的顶部中心?
  • 查看 Aarowaim 解决方案,坐标与立方体相同,但存在一些错误。尝试混合两个答案,这可能会奏效
【解决方案2】:
@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)
    }
}

这将绘制到玩家的位置。我无法想象它需要花费很多精力来调整它以绘制到点击的位置。

【讨论】:

  • 谢谢,我现在在四处移动时坐标的定位出现了奇怪的行为:) ...知道如何将坐标固定到立方体上...我可以解决留下的痕迹稍后...
  • 当我添加... playerX + xPosition, playerY + yPosition);我似乎在屏幕中间丢失了坐标? ...虽然坐标固定在立方体上:)
  • 现在一切正常 :) 谢谢菲尔!非常感谢!大帮助! :D
猜你喜欢
  • 2011-03-08
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多