我有一个Java Swing问题。我目前正在将游戏检查员编码为练习。我使用JLabels
的棋子片创建了ImageIcon
的棋子。我添加了MouseListener
来更新帧上标签的x和y位置,并使用ActionListener
基于计时器每隔5毫秒设置标签位置。它的工作原理是,当我用鼠标拖动标签时,标签会在屏幕上跳转(而不是用鼠标跟踪)。
有人知道造成这种情况的原因吗?是否有基于我目前的代码的简单解决方案?
我是新手,所以我意识到我可能完全采取错误的方法。我无法附加图像,但它只是一个80 x 80像素的正方形,前景中有一个纯黑色圆圈,背景是透明的。非常感谢!
package checkers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.*;
public class Piece2 extends JLabel implements
ActionListener, MouseListener, MouseMotionListener{
ImageIcon checkerIcon;
String color = null;
Timer t = new Timer(5, this);
int x, y, width = 80, height = 80;
public Piece2(int initX, int initY, String color){
this.x = initX;
this.y = initY;
this.color = color;
t.start();
setLocation(x, y);
setSize(width, height);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
addMouseMotionListener(this);
addMouseListener(this);
if(color.equals("Red")){
checkerIcon = new ImageIcon("/RedChecker.png");
}
else if(color.equals("Black")){
checkerIcon = new ImageIcon("/BlackChecker.png");
}
setIcon(checkerIcon);
}
@Override
public void actionPerformed(ActionEvent e) {
setLocation(x, y);
}
/**
* Mouse Event Listeners
*
*/
@Override
public void mouseDragged(MouseEvent e) {
this.x = e.getX();
this.y = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
x = x - (x % 50);
y = y - (y % 50);
}
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
//To test Piece
public static void main(String[] args){
Piece2 p1 = new Piece2(0, 0, "Black");
JFrame frame1 = new JFrame("Test");
frame1.setSize(800, 800);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(p1);
frame1.setVisible(true);
}
}