-2

I am creating a Blackjack card game through Java. The button I created is supposed to call the main method from the Blackjack class in order to start the game.

My problem is, when pressed the button stays blue and I am unable to type into the pop-up window. This is the Window class, the ActionPerformed method is supposed to call the Blackjack class.

import java.awt.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.Dimension;
import javax.swing.JButton;
import java.awt.event.*;

public class exampleWindow implements ActionListener
{

    public void createWindow()
    {
        JFrame frame = new JFrame("Blackjack");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel textLabel = new JLabel("Welcome to Blackjack!", SwingConstants.CENTER);
        textLabel.setPreferredSize(new Dimension(800, 600));
        textLabel.setFont(new Font("Zapfino", Font.BOLD, 36));
        frame.getContentPane().add(textLabel, BorderLayout.CENTER);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.getContentPane().setBackground(new Color(0,132,32));
        JButton start = new JButton();
        frame.getContentPane().add(BorderLayout.SOUTH, start);
        start.setText("Start Game");
        start.addActionListener(this);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    }

    public void actionPerformed(ActionEvent e)
    {
            Blackjack.main(null);
    }

    public static void main(String[] args)
    {
        exampleWindow e = new exampleWindow();
        e.createWindow();
    }
}

Here is the main class, Blackjack:

import java.util.Scanner;

public class Blackjack

{

    public static void main(String[] args)

    {

        System.out.println("Welcome to Blackjack! Please enter your name:");
        Scanner name = new Scanner(System.in);
        String playerName = name.nextLine();
        System.out.println("Place your bet: ");
        Scanner bet = new Scanner(System.in);
        int playerBet = bet.nextInt();
        int card1 = (int) Math.ceil(Math.random() * 11);
        int card2 = (int) Math.ceil(Math.random() * 11);
        int card3 = (int) Math.ceil(Math.random() * 11);
        int card4 = (int) Math.ceil(Math.random() * 11);
        System.out.println("Dealing Cards...");
        System.out.println(playerName + " has: " + card1 + " and " + card2);
        System.out.println("Dealer has: " + card3 + " and " + card4);
        Scanner answer = new Scanner(System.in);
        int playerTotal = card1 + card2;
        int dealerTotal = card1 + card2;
        String WoL = "";
        String DWoL = "";
        int stop = 0;
        if (playerTotal == 21)
        {
            System.out.println("BlackJack! You win: " + 2 * playerBet);
        }
        while (stop == 0)
        {
            System.out.println("Hit or Stand? (H/S)");
            String HoS = answer.nextLine();
            if(HoS.equals("h") || HoS.equals("H"))
            {
                playerTotal += (int) Math.ceil(Math.random() * 11);
                if(playerTotal > 21)
                {
                    System.out.println(playerName + " has: " + playerTotal + " --> Bust! You Lose: -" + playerBet);
                    WoL = "L";
                    stop++;
                }
                else if (playerTotal == 21)
                {
                    System.out.println(playerName + " has: " + playerTotal + " --> Blackjack! You win " + 2 * playerBet);
                    WoL = "W";
                    stop++;
                }
                else
                {
                    System.out.println(playerName + " has: " + playerTotal);
                }
            }
            else
            {
                stop++;
            }
        }


        if(WoL.equals("W") || WoL.equals("L"))
        {

        }
        else
        {
            while (dealerTotal <=16)
            {
                System.out.println("Dealer hits");
                dealerTotal += (int) Math.ceil(Math.random() * 11);
                if(dealerTotal > 21)
                {
                    System.out.println("Dealer has: " + dealerTotal + " --> Bust! You Win: " + 2 * playerBet);
                    DWoL="L";
                }
                else if (dealerTotal == 21)
                {
                    System.out.println("Dealer has: " + dealerTotal + " --> Blackjack! You lose: -" + playerBet);
                    DWoL="W";
                }
                else
                {
                    System.out.println("Dealer has: " + dealerTotal);
                }
            }
            if(DWoL.equals("W") || DWoL.equals("L"))
            {

            }
            else
            {
                System.out.println("Dealer stands on: " + dealerTotal);
            }
        }

        if(DWoL.equals("L") || DWoL.equals("W") || WoL.equals("W") || WoL.equals("L"))
        {

        }
        else if (dealerTotal == playerTotal)
        {
            System.out.println("Tie Game! No money exchanged");
        }
        else if (dealerTotal > playerTotal)
        {
            System.out.println("Dealer has higher cards. Dealer wins! You lose: -" + playerBet);
        }
        else
        {
            System.out.println(playerName + " has higher cards. " + playerName + " wins! You win: " + 2 * playerBet);
        }

   }

}
Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49
B. Lop
  • 31
  • 1
  • 5
  • `My problem is, when pressed the button stays blue and I am unable to type into the pop-up window` - what popup window? Post a proper [mcve] that demonstrates the problem. – camickr May 08 '17 at 16:27
  • 1
    My bet: you've got a threading problem. Possibly your Blackjack class has code that ties up the Swing event thread, such as `Thread.sleep` or `while (true)` or some other long loop, preventing the thread from performing its vital functions, and thus freezing your GUI. – Hovercraft Full Of Eels May 08 '17 at 16:30
  • 1
    But I agree, post a avlid [mcve] for us to tell. Your code above doesn't appear to contain the seeds of the error. – Hovercraft Full Of Eels May 08 '17 at 16:31
  • 1
    Don't mix console programs with GUI's -- that's your problem. If Blackjack is being run by a GUI, it should in fact **be** a Swing GUI. – Hovercraft Full Of Eels May 08 '17 at 16:51

1 Answers1

1

From what I can see right here, it is the Blackjack.main(null) performing a loop that never returns. With this call coming from the event dispatch thread (EDT), this would cause the UI to become unresponsive since the UI is processed on the EDT. Since you're combining a console application with the GUI, the UI will not receive any processing time until your main() function has returned. The input for the Scanner in the Blackjack class is the console's standard in. So you have a UI waiting for blackjack to finish from the console.

It's useful to think of the code running on the event dispatch thread as a series of short tasks. Most tasks are invocations of event-handling methods, such as ActionListener.actionPerformed. Other tasks can be scheduled by application code, using invokeLater or invokeAndWait. Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.

https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

My recommendation would be to look into javax.swing.SwingWorker. You can find a tutorial here: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

or javax.swing.Timer found here:

https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html

Edit

You need to redesign how you have your application structured if you plan on sticking with a GUI. If you wish to use Swing to run your Blackjack game, you could break up each action the game will perform into their own methods. This separates the "brains" from the visuals. You could then use a layer that combines the two. This is known as Model, View, Controller. The model would be a class containing the all the calculations and actions the game need to make, the view is you GUI and look-and-feel, and the controller is how user interactions on the view trigger actions in the model. http://www.oracle.com/technetwork/articles/javase/index-142890.html

  • 1
    Yours is a premature recommendation, unless you can see Blackjack's loop and we can't. We don't know yet if SwingWorker is the solution, and in fact it may be much better solved with a Swing Timer. – Hovercraft Full Of Eels May 08 '17 at 16:41
  • I apologize for lack of info, and appreciate everyone's help so far!! I added the main class, Blackjack in the original question. – B. Lop May 08 '17 at 16:50
  • @HovercraftFullOfEels thanks for the reminder about the Timer, and apologies for jumping the gun. B. Lop, you need to decide if you want a GUI or not. If you're going for a GUI I would look at a Model, View, Controller design. http://stackoverflow.com/questions/8693815/java-learning-mvc – quackenator May 08 '17 at 17:14