/** * Picks a card when a button is pressed. */ import javax.swing.*; import java.awt.GridLayout; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class PickACard extends JFrame implements ActionListener { public PickACard(String title) { super(title); setSize(300, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); button = new JButton("click to pick card"); button.addActionListener(this); add(button,BorderLayout.SOUTH); textArea = new JTextArea(); textArea.setEditable(true); textArea.setBackground(new Color(230,230,230)); textArea.setLineWrap(true); textArea.append("Your cards are:"); add(textArea,BorderLayout.CENTER); setVisible(true); } public void actionPerformed(ActionEvent event) { int cardIndex = (int) (52*Math.random()); textArea.append("\n"+cardName(cardIndex)); } /** Given an index from 0 to 51, determine the name of the card. * @param c the card index * @return the name of the card */ public String cardName(int c) { int suit = c/13; int face = c % 13; String suitName=""; switch(suit) { case 0: suitName="Diamonds"; break; case 1: suitName="Hearts"; break; case 2: suitName="Clubs"; break; case 3: suitName="Spades"; break; } String faceName=""; if (face == 0) faceName = "Ace"; else if (face < 10) faceName = ""+(face+1); else if (face == 10) faceName = "Jack"; else if (face == 11) faceName = "Queen"; else if (face == 12) faceName = "King"; return faceName + " of " + suitName; } public static void main(String[] args) { PickACard frame = new PickACard("Pick a Card"); } JTextArea textArea; JButton button; }