I am having trouble making use of a MouseMotionListener to make some card images be able to be dragged around the screen. What this program does is show a table of cards in a random order. The user will be able to drag any of the card images and move it anywhere in the window and have it stay there.
The problem I'm having is that the listener does not seem to ever get called and I cannot figure out why
mouse listener class
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MouseListener extends Card implements MouseMotionListener
{
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseDragged(MouseEvent arg0)
{
// TODO Auto-generated method stub
super.setx(arg0.getX());
super.sety(arg0.getY());
repaint();
}
@Override
public void mouseMoved(MouseEvent arg0)
{
// TODO Auto-generated method stub
}
}
the card class
import javax.swing.*;
import java.awt.*;
public class Card extends JPanel
{
private ImageIcon img= null;
private int x,y;
public void setx(int X)
{
x=X;
}
public void sety(int Y)
{
y=Y;
}
public Card(ImageIcon icon)
{
this.addMouseMotionListener(new MouseListener());
this.img = icon;
x=0;
y=0;
}
protected Card()
{
}
public void paint(Graphics g,int X, int Y)
{
img.paintIcon(this, g, X+x, Y+y);
}
}
and main
public static void main(String[] args)
{
/**
*@param args Not used for anything
*/
//load the card images
final ImageIcon blank = new ImageIcon("cardImages/gray.gif");
CardDeck deck = new CardDeck();
deck.shuffle();
//take all the cards off the deck now
final Card[] cardIcon = new Card[52];
for (int i = 0; i < 52; i++)
cardIcon[i]= deck.getCard();
//create a panel displaying the card image
JPanel panel = new JPanel()
{
private static final long serialVersionUID = 1L;
//paintComponent is called automatically by the JRE whenever
//the panel needs to be drawn or redrawn
public void paintComponent(Graphics g)
{
int x = 0,y = 20; //offsets used for drawing the cards
super.paintComponent(g);
//paint the blank cards:
blank.paintIcon(this, g, 20, 20);
blank.paintIcon(this, g, 20, 130);
blank.paintIcon(this, g, 20, 240);
blank.paintIcon(this, g, 20, 350);
//paint the other cards
for (int i = 0; i <52; i++)
{
if (i == 13) //start row two
{
x = 0;
y = 130;
}
else if (i == 26) //start row 3
{
x = 0;
y = 240;
}
else if (i == 39) //start row 4
{
x = 0;
y = 350;
}
x += 80;
//cardIcon[i].paintIcon(this, g, x+20, y);
cardIcon[i].setEnabled(true);
cardIcon[i].paint(g, x+20, y);
//cardIcon[i].setFocusable(true);
//cardIcon[i].setRequestFocusEnabled(isVisible());
}
}
};
//create & make visible a JFrame to contain the panel
JFrame window = new JFrame("Cards");
panel.setBackground(new Color(90,190,90));
window.add(panel);
window.setPreferredSize(new Dimension(1180,500));
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
The mouse listener is the only part of this code that doesn't work