-2

问题:如何设置我的 Shuffle 按钮的 ActionListener 来执行按钮声明的操作,即洗牌屏幕上显示的 3 张卡片(图像文件夹中的 54 张卡片)?每次我运行程序时它们都会随机出现,这很好,但我需要添加一个随机播放按钮,以便在无需重新启动程序的情况下进行这些更改。这是我到目前为止所得到的..

//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){

    }

}

}

无法创建新的作业标签(提示提示):) -此处不牵手-

4

2 回答 2

2

试试这个,它应该工作。这个想法是将 an 链接ActionEvent到每次点击按钮时要执行的代码。阅读本文了解详情。

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource() == shuffle) {
        // add code here for shuffling 3 cards
    }
}
于 2013-09-16T08:08:28.980 回答
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()
}

}

像这样带有防止卡片匹配的循环的东西在这里可能是合适的,因为它是您需要确认其唯一性的少量卡片。

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

于 2013-09-16T08:19:38.020 回答