I have a Java Swing question. I am currently coding the game checkers as an exercise. I created the checkers pieces as JLabels
with an ImageIcon
of the checkers piece. I added a MouseListener
to update the x and y locations of the label on the frame, and am using an ActionListener
to set the label location every 5 milliseconds based on a timer. It works except that the label jumps around the screen when I am dragging it with the mouse (instead of tracking with the mouse).
Does anybody know what is causing this? Is there an easy solution based on the code I currently have?
I am new to swing stuff so I realize I could be taking the wrong approach entirely. I am unable to attach the image, but it is just a 80 x 80 px square with a solid black circle in the foreground and the background is transparent. Thanks a lot!
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);
}
}