洗牌三张牌

时间:2013-09-16 07:51:48

标签: java shuffle

问题:如何设置我的随机播放按钮的ActionListener来执行按钮声明的操作,也就是说,将屏幕上显示的3张卡片(图像文件夹中的54张)洗牌?它们每次运行程序时都会随机出现,这很好,但是我需要添加一个shuffle按钮,允许这些更改发生而无需重新启动程序。 这是我到目前为止所拥有的......

//Jeffrey Zachary
//Advanced Java: Sept 15 2013
//Display 3 cards, shuffle them when called to do so

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

class DisplayCards extends JFrame implements ActionListener{
private JPanel cards;
private JButton shuffle;
private JLabel c1, c2, c3;
private Container contents;
private ImageIcon[] imIc;

 int cardA = 1 + (int)(Math.random() * 54);
 int cardB = 1 + (int)(Math.random() * 54);
 int cardC = 1 + (int)(Math.random() * 54);

//create variables to store the random number for card 
private ImageIcon firstCard = new ImageIcon("card/" + cardA + ".png");
private ImageIcon secondCard = new ImageIcon("card/" + cardB + ".png");
private ImageIcon thirdCard = new ImageIcon("card/" + cardC + ".png");

public DisplayCards(){
    super("Display three cards");
    contents = getContentPane();
    contents.setLayout(new BorderLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Creating card labels
c1 = new JLabel(firstCard, JLabel.CENTER);
c2 = new JLabel(secondCard, JLabel.CENTER);
c3 = new JLabel(thirdCard, JLabel.CENTER);

    //Creating panel
cards = new JPanel(new BorderLayout());

    //Creating button
shuffle = new JButton("Shuffle");
shuffle.addActionListener(this);
    //Adding buttons
cards.add(shuffle, BorderLayout.PAGE_END);

    //Adding labels
cards.add(c1, BorderLayout.LINE_START);
cards.add(c2, BorderLayout.CENTER);
cards.add(c3, BorderLayout.LINE_END);
contents.add(cards, BorderLayout.CENTER);
setResizable(false);
setSize(255, 177);
setVisible(true);

}
public static void main(String[] args) {
    DisplayCards dc = new DisplayCards();

}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == shuffle){

    }

}

}

无法创建新的家庭作业标签(提示提示):) - 不能在这里牵手 -

2 个答案:

答案 0 :(得分:2)

试试这个,它应该有效。我们的想法是在每次按下按钮时将ActionEvent链接到您想要执行的代码。请阅读this了解详情。

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == shuffle) {
        // add code here for shuffling 3 cards
    }
}

答案 1 :(得分:2)

   @Override
    public void actionPerformed(ActionEvent e) {
    if(e.getSource() == shuffle) {
    cardA = 1 + (int)(Math.random() * 54);
    while(cardB == cardA){
        cardB = 1 + (int)(Math.random() * 54);
        }
    while (cardC == cardB || cardC == cardB){
        cardC = 1 + (int)(Math.random() * 54);
    }

    firstCard = new ImageIcon("card/" + Integer.toString(cardA) + ".png");
    secondCard = new ImageIcon("card/" + Integer.toString(cardB) + ".png");
    thirdCard = new ImageIcon("card/" + Integer.toString(cardC) + ".png");
    DisplayCards()
}

}

这样的环路可以防止卡片匹配,这可能是合适的,因为你需要确认其中的唯一性。

循环不断创建一个随机数,直到它与之前的数字不匹配。完成后,重新选择相应的卡片并重新显示它们。