简体   繁体   中英

How to flip a card in java applets

I need to have a program that when I click on the card it will flip to the back side of the card and when I click on it again it will show the face again. Please Help, I have it to when I click the card it will show the back of it but how do I get it to show the front again?

import java.awt.Button;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.JApplet;

public class DealCard extends JApplet implements ActionListener, MouseListener {

Random gen = new Random();
Button dealButton = new Button("Deal");
int card1 = 0;
Image[] card = new Image[53];
Image[] back= new Image[1];
int number = 0;

public void init() {

    setSize(200, 200);
    setLayout(null);

    for (int i = 0; i < 53; i++) {
        card[i] = getImage(getCodeBase(), "card" + (i + 1) + ".gif");
    }
    dealButton.setBounds(100, 200, 80, 30);

    add(dealButton);

    dealButton.addActionListener(this);

    dealButton.setEnabled(true);

    addMouseListener(this);
}

public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(card[card1], 100, 100, 82, 82, this);
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == dealButton) {
        card1 = gen.nextInt(52);
    }
    repaint();
}

public void mouseClicked(MouseEvent e){
    int x = e.getX();
    int y = e.getY();
    if(x > 100 && x < (100+82) && y > 100 && y < (100+82)){

    card1 = 52;
    System.out.println(card1);
    repaint();
    e.consume();

    }
}
public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
}

public void mouseReleased(MouseEvent e) {
}
}

You need a boolean value to state whether the card is facing up or not.

Then add a condition to your draw statement that checks if the card is facing up or not.

Hope that helps.


You should also add a back card image, which does not need to be an array as it is just one.

Image back= new Image();

Or alternatively make card[0] your back card Image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM