Hot questions for Using Applets in jbutton

Question:

I am working on a slot machine in Java and so far I created a button that will randomly generate two pictures. For some reason one of the pictures shows up while the other picture does not. I do not understand the issue as the code for both of these pictures is exactly the same. Here is my code. Please help!

import java.applet.*;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JApplet;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.imageio.*;
import java.net.URL;
import java.io.*;
import java.awt.image.*;





public class slotmachine extends JApplet implements Runnable {
  JButton b1 = new JButton("START");
  JPanel p;
  int int1, int2;
  BufferedImage img= null;
  BufferedImage img2 = null;
  BufferedImage img3 = null;
  BufferedImage img4 = null;
  BufferedImage img5 = null;
  BufferedImage img6 = null;
  BufferedImage img7 = null;
  BufferedImage img8 = null;
  BufferedImage img9 = null;
  BufferedImage img10 = null;
  public slotmachine(){
    init();    
  }


  public void init() {

    this.setLayout(null);
    this.setSize(10000,10000);

    b1.setBounds(100,100,100,100);
    b1.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e){
        Random random1 = new Random();
        int1 = random1.nextInt(10);
        Random random2 = new Random();
        int2 = random2.nextInt(10);
        repaint();

      }


    });


    getContentPane().add(b1);

    try {

      img = ImageIO.read(new File("question.png"));
      img2 = ImageIO.read(new File("banana.png"));
      img3 = ImageIO.read(new File("chocolate.png"));
      img4 = ImageIO.read(new File("icecream.png"));
      img5 = ImageIO.read(new File("bell.png"));
      img6 = ImageIO.read(new File("apple.png"));
      img7 = ImageIO.read(new File("money.png"));
      img8 = ImageIO.read(new File("number-7.png"));
      img9 = ImageIO.read(new File("necklace.png"));
      img10 = ImageIO.read(new File("gloves.png"));
    } catch (IOException e) {
    }  

    repaint();

    this.setVisible(true);  
  }


  public void paint(Graphics g) {
    super.paintComponents(g);
    g.drawString("Int 1 is" + int1,30,30);
        g.drawString("Int 2 is" + int2,30,80);
    switch (int1) {
      case 0:

        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img, 300, 500, this);
        break;
      case 1:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img2,300,500,this);
        break;
      case 2:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img3,300,500,this);
        break;
      case 3:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img4,300,500,this);
        break;
      case 4:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img5,300,500,this);
        break;
      case 5:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img6,300,500,this);
        break;
      case 6:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img7,300,500,this);
        break;
      case 7:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img8,300,500,this);
        break;
      case 8:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img9,300,500,this);
        break;
      case 9:
        g.setColor(Color.white);
        g.fillRect(300,300,300,500);
        g.drawImage(img10,300,500,this);
        break;

    }


    switch (int2) {
      case 0:

        g.setColor(Color.white);
        g.fillRect(300,300,800,500);

        g.drawImage(img, 800, 500, this);
        break;
      case 1:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img2,800,500,this);
        break;
      case 2:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img3,800,500,this);
        break;
      case 3:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img4,800,500,this);
        break;
      case 4:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img5,800,500,this);
        break;
      case 5:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img6,800,500,this);
        break;
      case 6:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img7,800,500,this);
        break;
      case 7:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img8,800,500,this);
        break;
      case 8:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img9,800,500,this);
        break;
      case 9:
        g.setColor(Color.white);
        g.fillRect(300,300,800,500);
        g.drawImage(img10,800,500,this);
        break;

    }

        this.setVisible(true);


  }

}

Answer:

    img10 = ImageIO.read(new File("gloves.png"));
} catch (IOException e) {
}  

There are two problems in that code.

  1. A sand-boxed applet cannot use a File, and an applet with all permissions can only use a File that exists on the client machine. Since these images are apparently an application resource (i.e. supplied by you) they need to be on the server (or at least on the run-time class-path of the applet) and be loaded by URL.
  2. The catch is ignoring exceptions! Change it to:

    } catch (IOException e) {
        e.printStackTrace();
    }  
    

    Of course, be sure the Java Console is configured to show. If there is no output at the default level, raise the level and try it again.

Question:

I'm making a program that has 2 screens, a title and a game screen. If the user clicks "Play", they can proceed to the next screen. However, on the next screen if the user tries to press the button "Keep Going", nothing happens. I want to know why this is and if anyone can fix it. Thanks, and here is my code:

import java.applet.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class ZombieDice extends Applet implements ActionListener
{
Panel p_card;
Panel card1, card2;
CardLayout cdLayout = new CardLayout ();

int shotguns = 0;
int brains = 0;
int p1b = 0;
int p2b = 0;

JLabel pic1;
JLabel pic2;
JLabel pic3;

public void init ()
{
    p_card = new Panel ();
    p_card.setLayout (cdLayout);
    screen1 ();
    screen2 ();
    resize (600, 500);
    setLayout (new BorderLayout ());
    add ("Center", p_card);
}


public void screen1 ()
{
    card1 = new Panel ();
    JLabel logo = new JLabel (createImageIcon ("logo.jpg"));

    JButton play = new JButton (createImageIcon ("play.jpg"));
    play.setActionCommand ("2");
    play.addActionListener (this);

    JButton quit = new JButton (createImageIcon ("quit.jpg"));
    quit.setActionCommand ("quit");
    quit.addActionListener (this);

    card1.add (logo);
    card1.add (play);
    card1.add (quit);
    setBackground (Color.red);

    p_card.add ("1", card1);
}


public void screen2 ()
{
    card2 = new Panel ();
    JLabel player = new JLabel ("Player 1             ");
    player.setFont (new Font ("Vinque", Font.BOLD, 20));

    JLabel shotgun = new JLabel ("Shotguns: " + shotguns + "          ");
    shotgun.setFont (new Font ("Vinque", Font.BOLD, 14));
    JLabel brain = new JLabel ("Braaainss: " + brains);
    brain.setFont (new Font ("Vinque", Font.BOLD, 14));

    JLabel p1brains = new JLabel ("Player 1 Ate: " + p1b + " Braaiinnss            ");
    p1brains.setFont (new Font ("Vinque", Font.BOLD, 16));

    JLabel p2brains = new JLabel ("Player 2 Ate: " + p2b + " Braaiinnss");
    p2brains.setFont (new Font ("Vinque", Font.BOLD, 16));

    pic1 = new JLabel (createImageIcon ("zombie.jpg"));
    pic2 = new JLabel (createImageIcon ("zombie.jpg"));
    pic3 = new JLabel (createImageIcon ("zombie.jpg"));

    JButton keepgoing = new JButton (createImageIcon ("keepgoing.jpg"));
    keepgoing.addActionListener (this);
    keepgoing.setActionCommand ("kg");

    JButton stopscore = new JButton (createImageIcon ("stopAndScore.jpg"));
    keepgoing.addActionListener (this);
    keepgoing.setActionCommand ("ss");

    JButton nextplayer = new JButton (createImageIcon ("nextPlayer.jpg"));
    nextplayer.addActionListener (this);
    nextplayer.setActionCommand ("np");

    card2.add (player);
    card2.add (shotgun);
    card2.add (brain);
    card2.add (p1brains);
    card2.add (p2brains);
    card2.add (pic1);
    card2.add (pic2);
    card2.add (pic3);
    card2.add (keepgoing);
    card2.add (stopscore);
    card2.add (nextplayer);

    p_card.add ("2", card2);
}


public void actionPerformed (ActionEvent e)
{
    if (e.getActionCommand ().equals ("2"))
        cdLayout.show (p_card, "2");

    if (e.getActionCommand ().equals ("kg"))
    {
        int n = (int) ((Math.random () * 9) + 1);
        {
            if (n == 1)
                pic1.setIcon (createImageIcon ("greenBrain.jpg"));
            else if (n == 2)
                pic1.setIcon (createImageIcon ("greenFootPrints.jpg"));
            else if (n == 3)
                pic1.setIcon (createImageIcon ("greenShotGun.jpg"));
            else if (n == 4)
                pic1.setIcon (createImageIcon ("redBrain.jpg"));
            else if (n == 5)
                pic1.setIcon (createImageIcon ("redFootPrints.jpg"));
            else if (n == 6)
                pic1.setIcon (createImageIcon ("redShotGun.jpg"));
            else if (n == 7)
                pic1.setIcon (createImageIcon ("yellowBrain.jpg"));
            else if (n == 8)
                pic1.setIcon (createImageIcon ("yellowFootPrints.jpg"));
            else
                pic1.setIcon (createImageIcon ("yellowShotGun.jpg"));
        }
        int n2 = (int) ((Math.random () * 9) + 1);
        {
            if (n2 == 1)
                pic2.setIcon (createImageIcon ("greenBrain.jpg"));
            else if (n2 == 2)
                pic2.setIcon (createImageIcon ("greenFootPrints.jpg"));
            else if (n2 == 3)
                pic2.setIcon (createImageIcon ("greenShotGun.jpg"));
            else if (n2 == 4)
                pic2.setIcon (createImageIcon ("redBrain.jpg"));
            else if (n2 == 5)
                pic2.setIcon (createImageIcon ("redFootPrints.jpg"));
            else if (n2 == 6)
                pic2.setIcon (createImageIcon ("redShotGun.jpg"));
            else if (n2 == 7)
                pic2.setIcon (createImageIcon ("yellowBrain.jpg"));
            else if (n2 == 8)
                pic2.setIcon (createImageIcon ("yellowFootPrints.jpg"));
            else
                pic2.setIcon (createImageIcon ("yellowShotGun.jpg"));
        }
        int n3 = (int) ((Math.random () * 9) + 1);
        if (n3 == 1)
            pic3.setIcon (createImageIcon ("greenBrain.jpg"));
        else if (n3 == 2)
            pic3.setIcon (createImageIcon ("greenFootPrints.jpg"));
        else if (n3 == 3)
            pic3.setIcon (createImageIcon ("greenShotGun.jpg"));
        else if (n3 == 4)
            pic3.setIcon (createImageIcon ("redBrain.jpg"));
        else if (n3 == 5)
            pic3.setIcon (createImageIcon ("redFootPrints.jpg"));
        else if (n3 == 6)
            pic3.setIcon (createImageIcon ("redShotGun.jpg"));
        else if (n3 == 7)
            pic3.setIcon (createImageIcon ("yellowBrain.jpg"));
        else if (n3 == 8)
            pic3.setIcon (createImageIcon ("yellowFootPrints.jpg"));
        else
            pic3.setIcon (createImageIcon ("yellowShotGun.jpg"));
    }
}


protected static ImageIcon createImageIcon (String path)
{
    java.net.URL imgURL = ZombieDice.class.getResource (path);
    if (imgURL != null)
    {
        return new ImageIcon (imgURL);
    }
    else
    {
        System.err.println ("Couldn't find file: " + path);
        return null;
    }
}
}

Answer:

Maybe you should have a closer look at these two blocks...

JButton keepgoing = new JButton("kg", createImageIcon("keepgoing.jpg"));
keepgoing.addActionListener(this);
keepgoing.setActionCommand("kg");


JButton stopscore = new JButton("ss", createImageIcon("stopAndScore.jpg"));
keepgoing.addActionListener(this);
keepgoing.setActionCommand("ss");

See anything funny?

Question:

I want money1 button to be below the Jlabel saying fillmeup but when I do try to add a button it goes to the right of Label not under it. I am using an applet and using JButtons. Any advice would be much appreciated.

Here is the GUI picture

The blackJack game I am trying to make

    setBackground( new Color(130,50,40) );
    setLayout( new BorderLayout(3,3) );

    BlackjackCanvas board = new BlackjackCanvas();
    add(board, BorderLayout.CENTER);      

    Panel buttonPanel = new Panel();
    buttonPanel.setBackground(new Color(220,200,180));
    add(buttonPanel, BorderLayout.SOUTH);

    Panel buttonPane2 = new Panel();
    buttonPane2.setBackground(new Color(220,200,180));
    add(buttonPane2, BorderLayout.EAST);

    Panel buttonPane3 = new Panel();
    buttonPane3.setBackground(new Color(220,200,180));
    add(buttonPane3, BorderLayout.WEST);

    Button hit = new Button( "Hit!" );
    hit.addActionListener(board);
    hit.setBackground(Color.lightGray);
    buttonPanel.add(hit);

    Button stand = new Button( "Stand!" );
    stand.addActionListener(board);
    stand.setBackground(Color.lightGray);
    buttonPanel.add(stand);

    Button newGame = new Button( "New Game" );
    newGame.addActionListener(board);
    newGame.setBackground(Color.lightGray);
    buttonPanel.add(newGame);

    JLabel money = new JLabel( "Fill me up!" );
    money.setBackground(Color.lightGray);
    buttonPane2.add(money);

    Button money1 = new Button( "A rare commodity" );
    newGame.addActionListener(board);
    newGame.setBackground(Color.lightGray);
    buttonPane2.add(money1);

Answer:

I would consider referring to the docs here Java Layout Options

And setting buttonPane2 layout manager to the one that meets your needs.

This can be done using setLayout(new xxxLayout());

Question:

I have to create a TicTacToe game in an applet for a school project in Ready to Program Java 1.42. In the actionPerformed class I would like to simply set/edit the text of the first square on the top left to "X". I have used setActionCommand() on the JButton and have called getActionCommand() in the actionPerformed class. However in my if statement, I use getSource() so I can refer to the object itself and set/edit the text. Can I not use getActionCommand() and getSource() together? Thank you.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.JButton;

public class TicTacToe extends Applet implements ActionListener 
{
public void InitializeGame()
{

 setLayout(null);
 JButton Square1 = new JButton();
 Square1.setBackground(Color.white);
 Square1.setBounds(90,20,75,75);
 Square1.addActionListener(this);
 Square1.setActionCommand("s1");

 JButton Square2 = new JButton();
 Square2.setBackground(Color.white);
 Square2.setBounds(165,20,75,75);
 Square2.addActionListener(this);
 Square2.setActionCommand("s2");

 JButton Square3 = new JButton();
 Square3.setBackground(Color.white);
 Square3.setBounds(240,20,75,75);
 Square3.addActionListener(this);
 Square3.setActionCommand("s3");

 JButton Square4 = new JButton();
 Square4.setBackground(Color.white);
 Square4.setBounds(90,95,75,75);
 Square4.addActionListener(this);
 Square4.setActionCommand("s4");

 JButton Square5 = new JButton();
 Square5.setBackground(Color.white);
 Square5.setBounds(165,95,75,75);
 Square5.addActionListener(this);
 Square5.setActionCommand("s5");

 JButton Square6 = new JButton();
 Square6.setBackground(Color.white);
 Square6.setBounds(240,95,75,75);
 Square6.addActionListener(this);
 Square6.setActionCommand("s6");

 JButton Square7 = new JButton();
 Square7.setBackground(Color.white);
 Square7.setBounds(90,170,75,75);
 Square7.addActionListener(this);
 Square7.setActionCommand("s7");

 JButton Square8 = new JButton();
 Square8.setBackground(Color.white);
 Square8.setBounds(165,170,75,75);
 Square8.addActionListener(this);
 Square8.setActionCommand("s8");

 JButton Square9 = new JButton();
 Square9.setBackground(Color.white);
 Square9.setBounds(240,170,75,75);
 Square9.addActionListener(this);
 Square9.setActionCommand("s9");

 add(Square1);
 add(Square2);
 add(Square3);
 add(Square4);
 add(Square5);
 add(Square6);
 add(Square7);
 add(Square8);
 add(Square9);

}

public void init()
{
resize (400,300);
setBackground(Color.orange);

JButton Play = new JButton("Click to Play");                                 
Play.setBackground(Color.white);
Play.setForeground(Color.black);
Play.addActionListener(this);
add(Play);
}

public void actionPerformed(ActionEvent e)                         
{
removeAll();                                                       
setBackground(Color.pink);
InitializeGame();                                                   


if ( e.getActionCommand().equals( "s1" ) )
   {
   ((JButton)e.getSource()).setText("X");
   }

repaint(); 
} 

}

I expect to see "X" on the top left JButton. However the text does not appear when run.


Answer:

Inside actionPerformed() method, you need to have removeAll(), setBackground() and InitializeGame() calls inside a if block like I have shown below:

Otherwise, the whole UI resets every time you click any button. (Because you have added this same ActionListener to all the buttons.)

public void actionPerformed(ActionEvent e)
{
  if (((JButton) e.getSource()).getText().equals("Click to Play")) {
    removeAll();
    setBackground(Color.pink);
    InitializeGame();
  }

  if ( e.getActionCommand().equals( "s1" ) )
  {
    ((JButton)e.getSource()).setText("X");
  }

  repaint();
}