Sunday, February 13, 2011

Java Cards

I was just messing around with Java and made a small GUI to push some cards around on the screen. Here is the source for the whole thing. card_test.zip I was mainly testing out the JLabels on a layered layout type scenario. Next I'll be working on a full fledged Solitaire app, but this is just messing around on the screen, more or less a HELLO WORLD with cards.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


/**
 *
 * @author nick
 */
public class NewGui extends JFrame implements MouseListener , MouseMotionListener {

  
    private JLabel[] card = new JLabel[52] ; // Deck of Cards
    private int saveX, saveY,r_card; // temp save vars
    private boolean card_down = false; // for state
    private String[] card_list = new String[52];

    NewGui(){


        this.setTitle("Card Test");
        getLayeredPane().setLayout(null);
        for (int i = 0; i< 52; i++){

            // load the image
            Image image =Toolkit.getDefaultToolkit().getImage("./images/cards/" + (i + 1) + ".png");
            ImageIcon imageIcon = new ImageIcon(image);
            // Create our card
            card[i] = new JLabel(imageIcon);
            card[i].setBounds(0, 0, 80, 123);
            card[i].setOpaque(true);
            card[i].setBorder( BorderFactory.createLineBorder(Color.LIGHT_GRAY));
            // offset it by 1 pixel
            card[i].setLocation(0 + (i),0 + (i));
            // add it to the next layer
            getLayeredPane().add(card[i],i);

        }
        // for actions
        addMouseListener(this);
        addMouseMotionListener(this);

    };


    public void mouseDragged(MouseEvent e) {
        if (card_down){
            for (int j = 0; j < 7 ; j++){
                card[(r_card + j)%52].setLocation(e.getX() - 40 , e.getY() - 61 + (j*29));
                 getLayeredPane().moveToFront(card[(r_card + j)%52]);
            }
        }
    }

    public void mousePressed(MouseEvent e) {
        card_down = true;
        // grab a random card
        r_card = (int)(52.0 * Math.random());
    }
    public void mouseReleased(MouseEvent e) {
        card_down = false;
    }

    public void mouseMoved   (MouseEvent e) {}  // ignore these events
    public void mouseClicked (MouseEvent e) {}
    public void mouseEntered (MouseEvent e) {}
    public void mouseExited  (MouseEvent e) {}

    public static void main(String[] args) {
        // open a single frame and minimal setup
        NewGui frame = new NewGui();
        frame.setSize(800,600);
        frame.setLocation (100,100);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

No comments:

Post a Comment