JLabel changing on it's own - java

I've been working on what should be a relatively simple game, Mormon Sim. The goal is to hold a successful conversation while going door to door. It's pretty simple, on the click of a button, it changes a JLabel's text according to the button and method called. For example, using the Knock button will activate the method knockResponse, which will calculate if someone will come to the door or not. Based on the result of the calculation, someone will answer the door or you will be turned away. The problem is, after a few clicks, usually once the player gets past the knock check, the JLabel begins to revert itself back to other text, and back and forth between a few different things, sometimes completely disregarding the swing timers on them. I really have no idea what is going on here, and I can't really find a reason that this would happen. A whole week of thorough googling has yielded no similar problems or solutions. TL;DR Java has become self aware
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
//To do: ASCII art in JLabels
public class mainMenu implements ActionListener{
static JButton start = new JButton("Start!"), knock = new JButton("Knock"), talk = new JButton("Talk"), stats = new JButton("Stats");
static int level = 1, stamina = 100, knocking = 1, speech = 1, points = 0;
static JFrame frame = new JFrame("Mormon Sim");
static mainMenu game = new mainMenu();
static JLabel text = new JLabel(), knockSkill, speechSkill, staminaBar;
static JPanel DoorMenu = new JPanel();
JTextField name = new JTextField("Enter your name here", 25);
static String playerName;
public JPanel createStartMenu(){//JPanel for the start menu. Replaced on start click
JPanel startMenu = new JPanel();
JLabel instructions = new JLabel("<html>Welcome to Mormon Adventure, the first text-based mormon sim. Your goal is to <br>hold as many successful door to door<br>conversations as possible. Every successful conversation earns you a<br>skill point and a level. Level 15 is a win!<br>A conversation requires stamina as it goes on, find Orange Crush to replenish your stamina<html>");
startMenu.setLayout(null);
startMenu.setLocation(0, 0);
startMenu.setSize(500, 500);
start.setLocation(200, 300);
start.setSize(100, 50);
start.addActionListener(this);
startMenu.add(start);
instructions.setLocation(100, 100);
instructions.setSize(300, 200);
startMenu.add(instructions);
name.setSize(150, 25);
name.setLocation(100, 50);
name.addActionListener(this);
startMenu.add(name);
startMenu.setOpaque(true);
return startMenu;
}
public JPanel createDoorMenu(){//used for knocking, speaking, and going to the stat page. The problem is here
talk.setEnabled(false);
String knockText = "<html>You walk up the driveway of the next house on your<br>list. As you approach the door, you adjust your<br>tie, and smooth your hair. Your mouth is dry, and<br>you could really go for a bottle of orange crush.<br>You decide you should get one after this house.<br>Time to knock, someone is clearly home.<html>";
DoorMenu.setLayout(null);
DoorMenu.setLocation(0, 0);
DoorMenu.setSize(500, 500);
text = new JLabel(knockText);
text.setLocation(100, 150);
text.setSize(300, 200);
DoorMenu.add(text);
knock.setLocation(100, 400);
knock.setSize(100, 50);
knock.addActionListener(this);
DoorMenu.add(knock);
talk.setLocation(200, 400);
talk.setSize(100, 50);
talk.addActionListener(this);
DoorMenu.add(talk);
stats.setLocation(300, 400);
stats.setSize(100, 50);
stats.addActionListener(this);
DoorMenu.add(stats);
knockSkill = new JLabel("Knocking: " +knocking+ " Speech: " +speech+ " Level: " +level+ " Skill Points: " +points);
knockSkill.setLocation(100, 25);
knockSkill.setSize(500, 50);
DoorMenu.add(knockSkill);
DoorMenu.setOpaque(true);
return DoorMenu;
}
public JPanel createStatMenu(){//still doesn't do anything
JPanel statMenu = new JPanel();
return statMenu;
}
public static void knockResponse(){//generates a response from a knock based on knock level (1 <= x <= 10). Random number (1 <= y <= 10) is generated, level determines how many are successful
//max knock level will shatter the door. 50/50 chance of conversation or police. max speech + police will talk them into letting you go
knock.setEnabled(false);
Random rand = new Random();
int n = rand.nextInt(10) + 1;
if(n > knocking){//knock check loss
text.setText("<html>All you hear is someone yelling to go away...<br>Oh well. You chipper up and go to<br>the next house on your list. That orange Crush<br>will have to wait!<html>");
ActionListener taskPerformer = new ActionListener(){//delay the label reset
public void actionPerformed(ActionEvent evt){
text.setText("<html>You walk up the driveway of the next house on your<br>list. As you approach the door, you adjust your<br>tie, and smooth your hair. Your mouth is dry, and<br>you could really go for a bottle of orange crush.<br>You decide you should get one after this house.<br>Time to knock, someone is clearly home.<html>");
knock.setEnabled(true);
}
};
new Timer(1000, taskPerformer).start();
}
if(n <= knocking && knocking != 10){//successful knock check
knock.setEnabled(false);
stats.setEnabled(false);
text.setText("<html>Someone's coming to the door!<br>You straighten your hair and adjust your tie.<html>");
ActionListener taskPerformer = new ActionListener(){//delay the label reset
public void actionPerformed(ActionEvent evt){
text.setText("<html>The door opens, and you introduce yourself;<br>\"Hi! my name is " +playerName+ ". Have you accepted my homeboy JC as your lord and savior?\"<html>");//I couldn't really think of anything to make him say other than that
talk.setEnabled(true);
}
};
new Timer(1000, taskPerformer).start();
}
if(knocking == 10){//door breaks
text.setText("<html>You managed to shatter the door thanks to<br>your orange crush powered knocking skeelz.<html>");
n = rand.nextInt(1) + 1;
if(n == 0){//response check. Both are empty for now
text.setText("0");
}else if(n == 1){
text.setText("1");
}
}
}
public static void successCalc(){//calculate the success in talking to someone by
talk.setEnabled(false);
Random rand = new Random();
int n = rand.nextInt(10) + 1;
if(n <= speech && speech != 10){
level++;
points++;
text.setText("<html>After some time, your conversation is over.<br>That went well. Better than you thought.<br>As you leave, you feel a rumbling in your gut.<br>It soon becomes painful. You fall to<br>the ground, and a gleaming light comes from<br>your stomach, as a skill point bursts out.<br>You hear a faint \"dunananaaa...\"<html>");
talk.setEnabled(false);
knockSkill.setText("Knocking: " +knocking+ " Speech: " +speech+ " Level: " +level+ " Skill Points: " +points);
}else if(n > speech){
talk.setEnabled(false);
text.setText("<html>After a moment of you speaking, all they do<br>is start blaring death metal.<br>You decide it's time to leave!<html>");
}else if(speech == 10){
text.setText("<html>Your golden, heavenly voice convinces them<br>to convert immediately.<br>You run down to the nearest convenience store<br>and grab yourself an orange Crush. Bottled, of course.<html>");
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == start){
frame.getContentPane().removeAll();
frame.setContentPane(createDoorMenu());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
}else if(e.getSource() == knock){
knock.setEnabled(false);
knockResponse();
}else if(e.getSource() == talk){
talk.setEnabled(false);
successCalc();
}
playerName = name.getText();
}
public static void createAndShowGUI(){
JFrame.setDefaultLookAndFeelDecorated(false);
frame.setContentPane(game.createStartMenu());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();
}
});
}
}
Thanks for any help, I'm terrible at asking questions.

A Timer starts out repeating, by default. So, your timers are all firing every second, forever.
You ought to call setRepeats(false):
void doLater(ActionListener action, int delay) {
Timer timer = new Timer(delay, action);
timer.setRepeats(false);
timer.start();
}

Related

Coin flip simulation: Counting heads / tails

I am trying to simulate a coin flipper using Java and window builder. I have a button called "Flip" when that button is pressed the coin image changes depending on which number the random generator I created generates.
I now am trying to figure out a way to display the number of times the coin lands a heads or a tails in their respective JTextFields. I was thinking of using a counter, but I am struggling with how to update that into the text field, so far it only puts in that I have flipped each coin once.
I am very new to programming so any advice or guidance is much appreciated.
// this button flips the coin
btnFlip = new JButton("Flip");
btnFlip.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int headCounter = 0;
int tails = 0;
// this implements the random flip of the coin when the checkbox Run Multiple
// flips is unchecked
if (chckbxNewCheckBox.isSelected() == false) {
Random r = new Random();
int flipper = r.nextInt(2);
if (flipper == 1) {
lblImages.setIcon(new ImageIcon(FinalPrep.class.getResource("/finalPrep/heads.png")));
textFieldHeads.setText(String.valueOf(headCounter));
} else {
lblImages.setIcon(new ImageIcon(FinalPrep.class.getResource("/finalPrep/tails.png")));
textFieldTails.setText(String.valueOf(tails));
}
}
}
});
btnFlip.setFont(new Font("Tahoma", Font.PLAIN, 15));
panel_1.add(btnFlip);
You have to create something like 2 layers. One that contains the window itself along with the title (think of it like a receptor) then you have to create another "layer" that contains the buttons and the textfields. Something like this:
import javax.swing.*;
public class MyFrame extends JFrame {
private JPanel panel;
private JTextField textField;
private JButton button;
public MyFrame(){
panel = new JPanel(); //Step 1. Creation of a receptor
tfCount = new JTextField(10); //Step 2.
button = new JButton("Press Me"); //Creation of buttons & textfields.
panel.add(tfCount); //Step 3.
panel.add(button); //Add those graphics to the receptor
this.setContentPane(panel); //Step 4 Adjust the receptor to the object
this.setVisible(true);
this.setSize(400, 400);
this.setTitle("My 1st GUI!");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
(Sorry for the random example but you did not post any sample of code so I am trying to explain as best as I can)
Then you should put a "flag" depending of the number that was generated for example:
boolean flag = true; //Flag
int counter = 0; //The counter for the heads
int x; //The number you received from the generator
int counter_b; //The counter for the tails
if(x%2 == 0){ //If the number is even
flag = false; // You set down the flag
counter++; //And counter raises its value
}
else
counter_b++;
tfCount.setEditable(true); //This makes your textfield editable
tfCount.setText(String.valueOf(counter)); //And this prints the counter's value
Keep in mind that the counters for the tails and the heads are just examples for you to understand how to use "flags". I hope that I was able to help you because I am new too!! :)

Basic GUI java program in Eclipse keeps crashing

I am trying to make a game and in said game, there are 21 sticks and each person takes turns taking 1-4 sticks until there are no sticks left, if you cant take anymore sticks you lose. I have successfully made this program in eclipse but now I want to add GUI to it so I have to change the code. This code isn't complete but it crashes whenever I press the Go button which is my actionListener. I would type in a number to the text field, press go and it will just crash. How can I fix this?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sticks extends JFrame {
JButton Go;
JTextField tf1, tf2;
static JTextField sttf;
JLabel startTake;
static JLabel errorTake;
JLabel uTake;
JLabel compTake;
public Sticks() {
setLayout(new GridLayout(5, 2, 5, 5));
startTake = new JLabel("How many sticks do you want to take? (1-4)");
add(startTake);
sttf = new JTextField();
add(sttf);
errorTake = new JLabel("Hello");
add(errorTake);
Go = new JButton("Go");
add(Go);
uTake = new JLabel("");
add(uTake);
compTake = new JLabel("");
add(compTake);
// tf1 = new JTextField();
// add(tf1);
// TakeP = new JLabel("One stick taken");
// add(TakeP);
event e = new event();
Go.addActionListener(e);
}
public static class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
int numSticks = 21;
int numToTake = 0;
int randomNum = 0;
while (numSticks > 0) {
try {
int num = (int) (Double.parseDouble(sttf.getText()));
int NumSticks = numSticks - num;
errorTake.setText("There are: " + numSticks + " left");
Robot Rob = new Robot();
numToTake = (int)Math.random() * 4 + 1;
errorTake.setText("There are: " + numSticks + " left");
}
catch (Exception ex) {
ex.printStackTrace();;errorTake.setText("There is a problem");
}
}
}
}
public static void main(String[] args) {
Sticks gui = new Sticks();
gui.setDefaultCloseOperation(EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 200);
gui.setTitle("Nice Game");
}
}
Everytime you click the "Go" button, your actionPerformed fires, and it doesn't wait for user input at all. This is your problem line.
public static class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
//...
int num = (int) (Double.parseDouble(sttf.getText()));
//...
}
}
sttf.getText() always returns "" because sttf is empty, the program doesn't wait for user input unlike Scanner(System.in).
Makes sense that you don't get any Exceptions because it just runs and finishes the game without giving the user enough time to input anything. Are you sure the console doesn't print "Numbers only!", though? Because I've never tried to parse an empty String before.
Okay I've been reading this all wrong, sorry.
Your actionListener generates a new game everytime you click it, because you set your numSticks to 21 at each click. Looking forward, I don't think that's a good idea unless you want to take the same amount of sticks the whole way until the game ends. Same thing stands. If you input a value in sttf, the program won't wait for you to change it because it'd keep using that value until your while loop ends.

java dynamic display JLabel

I have a button. If I click this button, a popup appears. The popup asking me to write a word. if I write a word 6 letter, 6 jlabels appear, but if I enter another word shorter, the JLabels do not disappear
I want my JLabels may decrease according to a shorter word, but i don't know :(
thx for your great help !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//BUTTON 1 WORD
Controller c = new Controller();
try {
final JFrame popup = new JFrame();
//display popup
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
//control the length of the word
c.controleW(word);
//display jlabel lenght of word
keyNumber.setText(String.valueOf(word.length()));
//JLabels displays depending on the word length
int pixels = 50;
for (int i = 0; i < word.length(); i++) {
label = new JLabel("_");
label.setBounds(pixels, 200, 30, 30);
add(label);
label.repaint();
pixels += 20;
}
} catch (Exception e) {
System.out.println(e);
}
}
And my class to control the length of the word
public String controleW(String word) {
boolean flag = false;
final JFrame popup = new JFrame();
while (flag == false) {
if (word.length() <= 3) {
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
} else {
flag = true;
}
};
return null;
}
You are always adding labels in your method, never removing any, thus running the code twice will indeed add labels twice. To fix it, you can simply add a removeAll(); in jButton1ActionPerformed before you add any labels. This makes sure that any previously added components will be removed.

Instance not storing in array. What do I have wrong here?

I am having issues trying to get this program to run, the applet loads, but when I enter a number and click ok, nothing seems to happen... I am not sure if I have an issue with the array or where my issue might lie.
I can't seem to figure out what exactly I am doing wrong.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
public class LargestApplet extends Applet implements ActionListener {
private static final long serialVersionUID = 1L;
int number =0;
double highNumber=-1;
double lowNumber=-1;
// Create components for applet
Label numberLabel = new Label("Enter a number:");
TextField numberField = new TextField(5);
Button okButton = new Button("OK");
Button cancelButton = new Button("Cancel");
Label highNumberOutputLabel = new Label("The Highest number is: 0 ");
public void init() {
add(numberLabel);
add(numberField);
numberField.requestFocus();
add(okButton);
add(cancelButton);
add(highNumberOutputLabel);
setSize(400, 500); // Sets the size of the applet window
}
public void actionPerformed(ActionEvent e) {
int number = 0, highNumber = -1;
if (numberField.getText().length() == 0) {
numberField.requestFocus();
JOptionPane.showMessageDialog(null,
"Number Cannot blank", "D A T A E R R O R",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
number = Integer.parseInt(numberField.getText());
} catch (NumberFormatException ex) {
numberField.requestFocus();
JOptionPane.showMessageDialog(null, "Number is invalid",
"D A T A E R R O R", JOptionPane.ERROR_MESSAGE);
return;
}
if (number < 0 || number > 10) {
numberField.requestFocus();
JOptionPane.showMessageDialog(null,
"Number must be between 0 and 10",
"D A T A E R R O R", JOptionPane.ERROR_MESSAGE);
return;
}
// Determine highest number
Integer [] numberAr = {number};
for(int i = 0; i < numberAr.length; i++)
{
number += numberAr[i];
if (numberAr[i] < lowNumber)
lowNumber = numberAr[i];
else if (numberAr[i] > highNumber)
highNumber = numberAr[i];
}
// Display the results
highNumberOutputLabel.setText("The Highest Number is: "
+ (highNumber));
}
}
You aren't adding the ActionListener to your buttons, and so pushing a button will have no effect. Fix that by calling addActionListener(this) on the relevant Button. Just having your GUI class extend ActionListener (which is also not a good idea in general) does not magically give buttons the action listener code, and pressing a button will have no effect if you don't first give it code to have a behavior.
More importantly, you should be coding with Swing (JApplet, JButton) not AWT. While Swing is admittedly out of date, AWT is prehistoric in comparison.
And most importantly for us, you should not be posting NullPointerExceptions with your question if you code isn't throwing any.

How can I change this code from an applet to a standalone application

Does anyone know how to make this applet into an application? After I remove "extends applet", It doesn't work. I'm not sure how to change it into an application and what to write after "extends."
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BlackjackGUI extends JApplet {
public void init() {
The init() method creates components and lays out the applet.
A BlackjackCanvas occupies the CENTER position of the layout.
On the bottom is a panel that holds three buttons. The
BlackjackCanvas object listens for events from the buttons
and does all the real work of the program.
setBackground( new Color(130,50,40) );
BlackjackCanvas board = new BlackjackCanvas();
getContentPane().add(board, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground( new Color(220,200,180) );
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton hit = new JButton( "Hit!" );
hit.addActionListener(board);
buttonPanel.add(hit);
JButton stand = new JButton( "Stand!" );
stand.addActionListener(board);
buttonPanel.add(stand);
JButton newGame = new JButton( "New Game" );
newGame.addActionListener(board);
buttonPanel.add(newGame);
} // end init()
public Insets getInsets() {
// Specify how much space to leave between the edges of
// the applet and the components it contains. The background
// color shows through in this border.
return new Insets(3,3,3,3);
}
// --- The remainder of this class consists of a nested class ---
class BlackjackCanvas extends JPanel implements ActionListener {
// A nested class that displays the card game and does all the work
// of keeping track of the state and responding to user events.
Deck deck; // A deck of cards to be used in the game.
BlackjackHand dealerHand; // Hand containing the dealer's cards.
BlackjackHand playerHand; // Hand containing the user's cards.
String message; // A message drawn on the canvas, which changes
// to reflect the state of the game.
boolean gameInProgress; // Set to true when a game begins and to false
// when the game ends.
Font bigFont; // Font that will be used to display the message.
Font smallFont; // Font that will be used to draw the cards.
BlackjackCanvas() {
// Constructor. Creates fonts and starts the first game.
setBackground( new Color(0,120,0) );
smallFont = new Font("SansSerif", Font.PLAIN, 12);
bigFont = new Font("Serif", Font.BOLD, 14);
doNewGame();
}
public void actionPerformed(ActionEvent evt) {
// Respond when the user clicks on a button by calling
// the appropriate procedure. Note that the canvas is
// registered as a listener in the BlackjackGUI class.
String command = evt.getActionCommand();
if (command.equals("Hit!"))
doHit();
else if (command.equals("Stand!"))
doStand();
else if (command.equals("New Game"))
doNewGame();
}
void doHit() {
// This method is called when the user clicks the "Hit!" button.
// First check that a game is actually in progress. If not, give
// an error message and exit. Otherwise, give the user a card.
// The game can end at this point if the user goes over 21 or
// if the user has taken 5 cards without going over 21.
if (gameInProgress == false) {
message = "Click \"New Game\" to start a new game.";
repaint();
return;
}
playerHand.addCard( deck.dealCard() );
if ( playerHand.getBlackjackValue() > 21 ) {
message = "You've busted! Sorry, you lose.";
gameInProgress = false;
}
else if (playerHand.getCardCount() == 5) {
message = "You win by taking 5 cards without going over 21.";
gameInProgress = false;
}
else {
message = "You have " + playerHand.getBlackjackValue() + ". Hit or Stand?";
}
repaint();
}
void doStand() {
// This method is called when the user clicks the "Stand!" button.
// Check whether a game is actually in progress. If it is,
// the game ends. The dealer takes cards until either the
// dealer has 5 cards or more than 16 points. Then the
// winner of the game is determined.
if (gameInProgress == false) {
message = "Click \"New Game\" to start a new game.";
repaint();
return;
}
gameInProgress = false;
while (dealerHand.getBlackjackValue() <= 16 && dealerHand.getCardCount() < 5)
dealerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() > 21)
message = "You win! Dealer has busted with " + dealerHand.getBlackjackValue() + ".";
else if (dealerHand.getCardCount() == 5)
message = "Sorry, you lose. Dealer took 5 cards without going over 21.";
else if (dealerHand.getBlackjackValue() > playerHand.getBlackjackValue())
message = "Sorry, you lose, " + dealerHand.getBlackjackValue()
+ " to " + playerHand.getBlackjackValue() + ".";
else if (dealerHand.getBlackjackValue() == playerHand.getBlackjackValue())
message = "Sorry, you lose. Dealer wins on a tie.";
else
message = "You win, " + playerHand.getBlackjackValue()
+ " to " + dealerHand.getBlackjackValue() + "!";
repaint();
}
void doNewGame() {
// Called by the constructor, and called by actionPerformed() if
// the use clicks the "New Game" button. Start a new game.
// Deal two cards to each player. The game might end right then
// if one of the players had blackjack. Otherwise, gameInProgress
// is set to true and the game begins.
if (gameInProgress) {
// If the current game is not over, it is an error to try
// to start a new game.
message = "You still have to finish this game!";
repaint();
return;
}
deck = new Deck(); // Create the deck and hands to use for this game.
dealerHand = new BlackjackHand();
playerHand = new BlackjackHand();
deck.shuffle();
dealerHand.addCard( deck.dealCard() ); // Deal two cards to each player.
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() == 21) {
message = "Sorry, you lose. Dealer has Blackjack.";
gameInProgress = false;
}
else if (playerHand.getBlackjackValue() == 21) {
message = "You win! You have Blackjack.";
gameInProgress = false;
}
else {
message = "You have " + playerHand.getBlackjackValue() + ". Hit or stand?";
gameInProgress = true;
}
repaint();
} // end newGame();
public void paintComponent(Graphics g) {
// The paint method shows the message at the bottom of the
// canvas, and it draws all of the dealt cards spread out
// across the canvas.
super.paintComponent(g); // fill with background color.
g.setFont(bigFont);
g.setColor(Color.green);
g.drawString(message, 10, getSize().height - 10);
// Draw labels for the two sets of cards.
g.drawString("Dealer's Cards:", 10, 23);
g.drawString("Your Cards:", 10, 153);
// Draw dealer's cards. Draw first card face down if
// the game is still in progress, It will be revealed
// when the game ends.
g.setFont(smallFont);
if (gameInProgress)
drawCard(g, null, 10, 30);
else
drawCard(g, dealerHand.getCard(0), 10, 30);
for (int i = 1; i < dealerHand.getCardCount(); i++)
drawCard(g, dealerHand.getCard(i), 10 + i * 90, 30);
// Draw the user's cards.
for (int i = 0; i < playerHand.getCardCount(); i++)
drawCard(g, playerHand.getCard(i), 10 + i * 90, 160);
} // end paint();
void drawCard(Graphics g, Card card, int x, int y) {
// Draws a card as a 80 by 100 rectangle with
// upper left corner at (x,y). The card is drawn
// in the graphics context g. If card is null, then
// a face-down card is drawn. (The cards are
// rather primitive.)
if (card == null) {
// Draw a face-down card
g.setColor(Color.blue);
g.fillRect(x,y,80,100);
g.setColor(Color.white);
g.drawRect(x+3,y+3,73,93);
g.drawRect(x+4,y+4,71,91);
}
else {
g.setColor(Color.white);
g.fillRect(x,y,80,100);
g.setColor(Color.gray);
g.drawRect(x,y,79,99);
g.drawRect(x+1,y+1,77,97);
if (card.getSuit() == Card.DIAMONDS || card.getSuit() == Card.HEARTS)
g.setColor(Color.red);
else
g.setColor(Color.black);
g.drawString(card.getValueAsString(), x + 10, y + 30);
g.drawString("of", x+ 10, y + 50);
g.drawString(card.getSuitAsString(), x + 10, y + 70);
}
} // end drawCard()
} // end nested class BlackjackCanvas
} // end class BlackjackGUI
If you're using an Applet-based approach for your game, you may just want to keep it that way. You can create a wrapper window which will hold your applet, which can then operate as normal. All you'll need to do is add a main method to your applet class, like so:
public static void main(String[] args) {
JFrame mainWindow = new JFrame("Blackjack"); // You can change "Blackjack" to anything, it will display that as the window title
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizeable(false); // If your applet can handle resizing, you can remove this line
BackjackGUI applet = new BlackjackGUI();
applet.init();
mainWindow.add(applet);
mainWindow.setSize(applet.getSize());
mainWindow.setVisible(true);
}
This will allow your app to run as both an applet and a stand-alone application.
Similar approach like Jake Kings way:
Move everything which isn't purely applet related from the init-method to a method, which produces the main panel. Most often you have such a main panel. Else you can define one.
In the applets init-method, call this new makeMainPanel ().
In parallel, create a main method, to start the application as a Swing JFrame. Create a mainframe, and add the same Panel with that method to your mainframe, and do purely application typical stuff in main.
Now you can call it either way.

Categories