Blackjack - using swing (Need Assistance)

Sir and Madam,
I just started learning Java with Java 5.0 Eclipse. I am taking a course for Java Programming. I am wondering if anyone is willing to help me to identify the missing sources or errors so that way I can learn more and more and have my codes runnable. I do not want to post my codes here because it is six pages in length.
If you are willing to help me, you can contact me at [email protected] with a subject "Java Assistance" so that way I can send the zip file to you unless you do not mind for me to post my code here.
My codes look pretty messy, I only learned since last March.
Really appreciate your assistance,
TT

Thanks for replying.. out of 6 pages of codes, I wrote most of them and they have no errors and test them with system.out.println. The output works very well until I added other class called Blackjack, the final class that contains all Swing and AWT containers/components. (I use Java 5.0)
The specific part of a whole 6 pages I need help is (check below):
(Note: class Card - create a single card contains both ImageIcon and value.
class Deck - create a whole deck with 52 cards contains two arrays of ImageIcon and values into Card[52], shuffle the cards etc..
class Player - create an array of class Card[10], calling for other card)
Now, the class Blackjack where it wont work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Blackjack extends JFrame implements ActionListener, Runnable
     //Creating three buttons that operates the game
     private JButton buttonHit = new JButton("Hit");
     private JButton buttonStay = new JButton("Stay");
     private JButton buttonReset = new JButton("New Game");     
     ImageIcon addIcon = null;
     boolean loaded = false;     
     //Indexing the array's cells
     int element = 0;     
     //Displays the result in message
     String message;     
     int iwidth;
     int iheight;     
     int cwidth = 1;
     int pad = 1;          
     //Counting the games played
     private int games = -1;
     //Creating an object of class Deck
     private Deck deck;     
     //Creating two objects of class Player (player vs dealer)
     private Player player;
     private Player dealer;     
     //Create a new game
     void NewGame()
          //Starts with Hit button to add the card
          //so Button "Stay" is not available.
          buttonHit.setEnabled(true);
          buttonStay.setEnabled(false);          
          //Creating a new game included two players
          player = new Player();
          dealer = new Player();          
          //Then shuffle the cards with two players awaits
          deck.shuffleCards();          
          //adds the game that start to play
          games++;
     //activites this function once the Button "HIT" got pressed.
     void hit()
          //Now two choices to press "Hit" or "Stay"
          buttonStay.setEnabled(true);          
          //Displays a new image card
          player.addCard(deck.deal());          
          if(player.getTotalValue() > 21)
               message = "You lost! (score:" + player.getTotalValue() + ")";
               //Disactivites all buttons except "New Game"
               buttonHit.setEnabled(false);
               buttonStay.setEnabled(false);
               return;
          message = "Score:" + player.getTotalValue();
     //activites this function once the Button "Stay" got pressed
     void stay()
          while(dealer.getTotalValue() < 17)
               dealer.addCard(deck.deal());
          if(dealer.getTotalValue() <= 21 && player.getTotalValue() < dealer.getTotalValue())
               message = "You lost! (" + player.getTotalValue()+
                         " - "+dealer.getTotalValue()+")";
          else if (player.getTotalValue() == dealer.getTotalValue())
               message = "You draw! (" + player.getTotalValue()+
                         " - "+dealer.getTotalValue()+")";
          else
               message = "You win! (" + player.getTotalValue()+
                         " - "+dealer.getTotalValue()+")";
          //disables buttons "Hit" or "Stay"
          buttonHit.setEnabled(false);
          buttonStay.setEnabled(false);
     //for ActionListener and ActionEvent communication
     public void actionPerformed(ActionEvent AEvt)
          //Only when Button "New Game" got pressed
          if(AEvt.getSource() == buttonReset)
               NewGame();
          //Only when Button "Hit" got pressed
          else if(AEvt.getSource() == buttonHit)
               hit();
          //Only when Button "Stay" got pressed
          else if(AEvt.getSource() == buttonStay)
               stay();
          invalidate();
     Blackjack(String title)
          super(title);
          getContentPane().setLayout(new FlowLayout());
          setSize(800,600);
          SetupButt();
          setVisible(true);
     void SetupButt()
          buttonHit.setToolTipText("Click here for other card.");
          buttonStay.setToolTipText("Click here for no more card.");
          buttonReset.setToolTipText("Click here to start a new game.");
          buttonHit.addActionListener(this);
          buttonStay.addActionListener(this);
          buttonReset.addActionListener(this);
          getContentPane().add(buttonHit);
          getContentPane().add(buttonStay);
          getContentPane().add(buttonReset);
     public static void main(String[] args)
          Blackjack Demo = new Blackjack("Blackjack Card Game");
          Demo.init();
     void init()
          Thread CardLoader = new Thread(this);
          CardLoader.start();
     ImageIcon[] load_images = new ImageIcon[52];
     public void run()
          deck = new Deck(this,load_images);          
          buttonHit.setEnabled(false);
          buttonStay.setEnabled(false);          
          iwidth = getSize().width;
          iheight = getSize().height;          
          this.invalidate();          
          invalidate();
     public void paintComponent(Graphics g)
if(pad == -1)
               pad = (iwidth - (cwidth * 2) - 4)/4;
          g.setColor(Color.GREEN);
          g.fillRect(0, 0, iwidth, iheight);
          g.setColor(Color.BLACK);
          g.fillRect(1,1, iwidth-2, iheight-2);
          g.setColor(Color.WHITE);
          g.drawString("YOU: ", pad, 40);
          g.drawString("DEALER:", (iwidth/2) + pad, 40);
          g.drawString(message, 5, iheight-20);
          if(games>0)
               g.drawString(games + " game(s) played...", 5,
                         iheight - 8);
          int nowCard;
          for(int i = 0; i < player.getCardCount(); i++)
               nowCard = player.getCards().GetValue();
(Error here)     g.drawImage(new ImageIcon("images/" + nowCard + ".gif"), pad,
                         70 + (20*(i-1)), this);
          for(int i = 0; i < dealer.getCardCount(); i++)
               nowCard = dealer.getCards()[i].GetValue();
(Error here) g.drawImage(new ImageIcon("images/" + nowCard + ".gif"), pad,
                         70 + (20*(i-1)), this);
          super.paintComponents(g);
Message was edited by:
Turyturbo
Message was edited by:
Turyturbo

Similar Messages

  • Web Guy Using Swing - Need Help With jComboBox

    I'm new to doing desktop Java development (come from a web application background) and am trying to accomplish migrating some of a web application's functionality to a desktop app for distribution. I'm already a bit stuck when it comes to using the jComboBox. What is intuitive to me in the web world would be to have one combo box/select box that after making a selection, it returns it's value so I could use that to run another query that would populate the next drop down menu. Populating the display of the combo box isn't the problem, that seems easy enough, but what I so far can't find is how I can attach a value to the combo box; that is for instance, having the drop down show a list of country names, and needing to have that list of country names correspond to a country code. For the web, you'd just have the option value tied to the code and the contents of the option be the name.
    Is this do-able? Am I completely thinking about this in the wrong way when working in desktop GUI things? I am using NetBeans 6.0 for my GUI layout and such, don't know if that helps or hurts matters. Also currently using Java 1.5.
    Any information or points in the right direction are greatly appreciated.
    Cheers.

    If I understand you correctly, you need to have a class that holds country name and country code, with a toString override method that returns just the country name (this is what the combobox shows). You then put an array of these objects in your jcombobox, obtain the selected object, get it's country code, and you're off and running.
    Edited by: Encephalopathic on Mar 31, 2008 3:26 PM

  • Hello, I need help with my macbook pro. It looks like I cannot install anything anymore. Everytime I try to install a new software, use the migration assistant or click the lock to make changes, it simply does not react.

    Hello, I need help with my macbook pro.
    It looks like I cannot install anything anymore. Everytime I try to install a new software, I simply get stuck during the installation type process. I put in my password, it does accept it, but it does not go any further.
    I tried to reset the password, put no password, repair the permissions, the disk but nothing will do. I nearly got stuck with the log in screen but finally succeeded in disabling it.
    So I thought I might try to create a new account but I cannot click the lock to make changes. It simply refuses to react.
    I am now thinking about using the migration assistant to save all my settings, data and so fourth, but again I get stuck when I have to type in my password. It accepts it but nothing happens...
    I guess it has something to do with the authorization process, but can't find anything on the internet about it... Can you help me out?
    I am running Lion 10.7.3.
    Regards,
    Nicolas.
    (I apologize if any grammatical/structural mistakes were to be found, english is not my mother-tongue. )

    You probably won't like this suggestion, but I suggest you reinstall Lion.
    First, backup your system. Next, reboot your system, press/hold the COMMAND-R keys to boot into the Recovery HD. Select 'Reinstall Mac OS X'. If you purchased Lion as an upgrade to Snow Leopard, the reinstall process will install Lion 10.7.3. If your system came preinstalled with Lion, you might still get Lion 10.7.2. Both installs are a total install of the OS. None of your apps or data will be impacted. Just the OS.

  • I need to install windows 7 on my iMac. I used the bootcamp assistant to partition the drive (101Gb). My bootcamp partition, when I am to choose a partitian, was deleted (by an instructor) I think I might need to repartition my hard drive. What do I do?

    I need to install windows 7 on my iMac. I used the bootcamp assistant to partition the drive (101Gb). My bootcamp partition, when I am to choose a partitian, was deleted (by an instructor) I think I might need to repartition my hard drive but I am not sure. What do I do? I haven't ruined my iMac have I?

    Help! I can't do my college homework if I can't run windows on my iMac! (school is on windows, limited access to the library)

  • Need  java code to perform refresh button action using swings and awt

    i need java code to perform refresh button action using swings and awt.please help me

    Wait ! Noboby ? OK, I'll do it
    public void onBtnAction ()
        if (!fresh)
            refresh ();
    }Seriously, did you expect anyone to answer such a cryptic question ?

  • Need a java code using swing that can do master configuration

    I need a java code using swing that can do master configuration.For example, in the 1st screen it will show all configuration checke boxes . According to those selected check box, it will show the needed panels sequentially and finnaly it will update many xml files.

    TapasB wrote:
    I need a java code .......and I wish you much luck in creating it. Please come back if you have a specific question on a specific part of your code that is not working quite right.

  • HT4796 I need to transfer my iTunes library, email and a few clean files from my PC to my new Mac.  I was about to use the Migration Assistant, however I am concerned that viruses on my PC will tag along.  Should I be concerned?

    I need to transfer my iTunes library, email and a few clean files from my PC to my new Mac.  I was about to use the Migration Assistant, however I am concerned that viruses on my PC will tag along.  Should I be concerned?

    No.

  • My wife was given a 5s and she sent her 4s to her daughter in Thailand to use. The problem is the 4s needs to have the imei number unlocked. We need assistance on how that can be done. We are long time Verizon customers.

    My wife was given a 5s and she sent her 4s to her daughter in Thailand to use. The problem is the 4s needs to have the imei number unlocked. We need assistance on how that can be done. We are long time Verizon customers.

    Your daughter will have to send it back to you. You will have to reactivate it on you line. You will then have to request to have it unlocked. See THIS thread for more information.

  • I need help with boot camp. "Back up the disk and use Disk Utility to format it as a single Mac OS Extended (Journaled) volume. Restore your information to the disk and try using Boot Camp Assistant again."

    This message appears every time I try to partition my disk:
    "Back up the disk and use Disk Utility to format it as a single Mac OS Extended (Journaled) volume. Restore your information to the disk and try using Boot Camp Assistant again."
    I verified my Macintosh HD disk on Disk utility and then tried to repair it, but I am unable to click the repair button.
    It says it's not available because the startup disk is selected.
    I don't know what to do or how to go about both these problems.
    Please, any suggestions?

    This message appears every time I try to partition my disk:
    "Back up the disk and use Disk Utility to format it as a single Mac OS Extended (Journaled) volume. Restore your information to the disk and try using Boot Camp Assistant again."
    I verified my Macintosh HD disk on Disk utility and then tried to repair it, but I am unable to click the repair button.
    It says it's not available because the startup disk is selected.
    I don't know what to do or how to go about both these problems.
    Please, any suggestions?

  • Help for a begginer using swing

    Basically I need help with a program for a school project. i am not looking for a quick answer but rather some pointers in the right direction. This is my first time using swing and my first project is to create a blackJack game. I am having trouble with functionality. there are problems on tab 2 with almost all the buttons. any help would be greatly appreciated. since i didnt have enough room for all my code i posted it online to be accessed at this site: [https://code.google.com/p/blackjackgui-alpha/]

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
    String betString = jTextField2.getText();
    betString = Integer.toString(bet);// TODO add your handling code here:
    total = total - bet;
      private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
        System.exit(0);        // TODO add your handling code here:
      private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String name = jTextField1.getText();
        String prefix = (String)jComboBox1.getSelectedItem();
        jLabel2.setText("Hello " + prefix + name + " and welcome to blackJack please press the tab labeled BlackJack");
          jLabel3.setText("Welcome to you personal blackJack game " + prefix + name + " your cards are" + card1 + "(" + card1s + ") and " + card2 + "(" +card2s + ")  your hand total is " + handTotal);
        jLabel5.setText("This is where you may see the Dealers information " + prefix + name);
      private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
              handTotal = card1 + card2;
              if(handTotal > 21)
                  jLabel3.setText("You busted press hit");
                  handTotal = 0;
              handTotal = card1+card2;
              dealerHandTotal = 0;
              dealerHandTotal = dealerCard1 + dealerCard2;
              handTotal = handTotal + card3;
          jLabel3.setText("You have hit and recieve " + card3 +   "your total is " + handTotal);
                jLabel5.setText("Dealer hits and recieves " + dealerCard1 + "(" + dealerCard1s + ") and " + dealerCard2 + "(" + dealerCard2s + ")  Dealer total is " + dealerHandTotal);
        if(handTotal > 21)
          jLabel3.setText("I am sorry, you busted with: " + handTotal + "Please press hit to begin a new round");
    handTotal = 0;
          card1=card1;
          card2 = card2;
        else if( handTotal == 21)
              total =  total + (bet*2);
          jLabel3.setText("BLACKJACK!!! your total is now: " + total);
          handTotal = 0;
          dealerHandTotal = 0;
        else if(handTotal == dealerHandTotal)
            jLabel3.setText("PUSH ...house automatically wins");
                       jLabel5.setText("PUSH ...house automatically wins");
                       handTotal = 0;
                       dealerHandTotal = 0;
        else if(dealerHandTotal < 17 || handTotal > dealerHandTotal) {
                    dealerHandTotal = dealerHandTotal + dealerCard1;
        else if(dealerHandTotal == 21)
            jLabel5.setText("DEALER GETS BLACKJACK!!")
                    dealerHandTotal = 0;
            dealerHandTotal = dealerCard1+dealerCard2;
            handTotal = 0;
            handTotal = card1 + card2;
      private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        jLabel3.setText("You have stood at " + handTotal);   // TODO add your handling code here:
      private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        jLabel3.setText("You have folded at your total of: " + handTotal);
        jLabel5.setText("You have folded at you total of:" + handTotal)
        handTotal = 0;
        dealerHandTotal = 0;
      }                  Sorry i thought it would be more convenient for the code to be on another page..my bad
    Edited by: rightWingNutJob on Mar 4, 2010 2:07 PM
    Edited by: rightWingNutJob on Mar 4, 2010 2:30 PM

  • I am trying to setup Microsoft office mail and need assistance  - I am receiving the error, unable to find server and DNS setting in the Network

    I am trying to setup Microsoft office mail and need assistance  - I am receiving the error, unable to find server and DNS setting in the Network

    Which version of OSX and what email provider are you using.

  • I can't use swing components in my applets

    When I write an applet without any swing components, my browser never has any trouble finding the classes it needs, whether they're classes I've written or classes that came with Java. However, when I try to use swing components it cannot find them, because it is looking in the wrong place:
    On my computer I have a directory called C:\Java, into which I installed my Java Development Kit (so Sun's classes are stored in the default location within that directory, wherever that is), and I store my classes in C:\Java\Files\[path depends on package]. My browser gives an error message along the lines of "Cannot find class JFrame at C:\Java\Files\javax\swing\JFrame.class"; it shouldn't be looking for this non-existent directory, it should find the swing components where it finds, for example, the Applet class and the Graphics class.
    Is there any way I can set the classpath on my browser? Are the swing components stored separately from other classes (I'm using the J2SE v1.3)?
    Thanks in advance.

    Without having complete information, it appears that you are running your applets using the browser's VM. Further, I assume you are using either IE or Netscape Navigator pre-v6. In that case, your browser only supports Java 1.1, and Swing was implemented in Java 1.2. You need to use the Java plug-in in order to use the Swing classes (see the Plug-in forum for more information), or else download the Swing classes from Sun and include them in your CLASSPATH.
    HTH,
    Carl Rapson

  • I have downloaded the 30 day free trial using Adobe Download Assistant but I do not know how to open it and start using it.

    I have downloaded the 30 day free trial using Adobe Download Assistant but I do not know how to open it and start using it.

    This was so annoying!! It took me a good couple of hours but i figured it out, you need to do the following: Go to the folder where you saved the download (in my case i saved it in My Downloads) -> click on 'Adobe Photoshop Elements 12' -> click on 'PSE 12' -> click on 'Setup' (select the icon which is a box with a shield) -> follow instructions and....voila! You will need to restart when it suggests so save anything else first, then when it reboots you should see the icon on your desktop....hpe this helps!

  • I used the migration assistant to transfer files from my PC to my Mac but it recreated my user profile from the PC and I wanted to transfer the files to the new different user profile I've setup on the Mac. How can I transfer everything now?

    I have an older Windows laptop and I am switching to a new MacBook Air. The main user on the Windows laptop is going to be different than the main user on the MacBook. I used the migration assistant to transfer data to the MacBook but it recreated the whole older profile on the new Mac when I just wanted to pull everything over into the new user profile I had already created on the new MacBook. How can I go about putting the data over into the new user profile and erasing the older other user profile it recreated? Would I erase the old user profile on the new Mac and start over with the migration assistant using some setting I missed that lets me pull the data over to the new main user on the MacBook? Or is there a way to rename the old user profile on the Mac to match what I want the new username/password to be somehow?
    Or would it be best to back the data I really need from the old PC onto an external HD and then copy it over to the new Mac from the external HD?
    Looking for advice on how to best go about this. On the old PC I had multiple profiles and it was awkward. On the new Mac I just want a single profile for the primary user and both users will just share the same user profile. I wasn't sure if the Migration Assistant only let you recreate entire profiles or if there was a way to just import data from the old PC's primary profile into the new Mac's new primary profile with some setting adjustment.
    Data would be docs, pics, bookmarks, music. Fairly basic.
    Thanks for any and all advice,
    -Crosscourier.

    Look in the /Users/ folder.

  • How can i connect multiple forms using swings or applets(AWT) & with D-Base

    Hello Friends,
    I am Sreedhar from Hyderabad. working as a java developer in a small organization. I got a challenge to work on java stand alone (desktop) application. Basically our company is based on SCM(Supply Chain Management), I never work before using swings and AWT. now my present challenge is to develope an application on swings and AWT using Net Beans IDE. but i am unble find the code to connect one form to another form, i want to develop similar application like a web application , suppose if i click on OK button it has to connect next form. in the next for it has to take user name and password should allow me to access main form. please help me about this topic, if anybody interested i can send u the screen shots and i can post to ur mail. please help me as soon as possible,

    sreedharkommuru wrote:
    Hello Friends,
    I am Sreedhar from Hyderabad. working as a java developer in a small organization. I got a challenge to work on java stand alone (desktop) application. Basically our company is based on SCM(Supply Chain Management), I never work before using swings and AWT. now my present challenge is to develope an application on swings and AWT using Net Beans IDE. but i am unble find the code to connect one form to another form, i want to develop similar application like a web application , suppose if i click on OK button it has to connect next form. in the next for it has to take user name and password should allow me to access main form. please help me about this topic, if anybody interested i can send u the screen shots and i can post to ur mail. please help me as soon as possible,There is no magic, you need to spend a good amount of time in tutorials, here is a good one to start off with:
    [The Really Big Index|http://java.sun.com/docs/books/tutorial/reallybigindex.html]
    Here are a few tips:
    1 - Do not mix AWT and SWING: it'll just cause you headaches in the long run that you cannot fix without refactoring to properly not mix the 2 together.
    2 - You use JDBC to access the database
    3 - You make accessors/constructors to pass parameters that you need from one form to another.
    Have fun.

Maybe you are looking for