Member Avatar for Member #413109

Hello again everyone, on my recent thread about my rock, paper, scissors program, I had trouble running it from Applet to JApplet and that problem was solved. So far, I've added many functions for the program such as menus, checking your score, resetting the score, and setting the number of games. So far everything looks great, but I'm having problems of making images of rock, paper, and scissors to appear and disappear when either the player or computer picks them. For example, if I click on the "Rock" button, the image of the rock should show on the player side excluding the paper and scissors images. This applies for the computer side as well. Here is what I have for the program:

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

public class RPS extends JApplet implements ActionListener
{
    private JButton rockButton;
    private JButton scissorsButton;
    private JButton paperButton;
    private String buttonPressed = "";
    private int computerValue = -1;
    private int myValue;
    private int playerScore = 0;
    private int computerScore = 0;
    private int drawScore = 0;
    private int pFinalScore = 0;
    private int cFinalScore = 0;
    private int numberOfGames = 5;
    Image pRock, pPaper, pScissors, cRock, cPaper, cScissors;

    //boolean flip = false;
	//JLabel picLabel;
	//JLabel picLabel2;
	//JLabel picLabel3;
	//JLabel comLabel;
	//JLabel comLabel2;
	//JLabel comLabel3;
	//Image img1;

    public void init()
    {
		Container c = getContentPane();

		c.setBackground(Color.white);
		c.setLayout(null);
		//URL url = getClass().getResource("rock.jpg");
		//ImageIcon pRock = new ImageIcon(url);
		//ImageIcon pPaper = new ImageIcon("paper.jpg");
		//ImageIcon pScissors = new ImageIcon("scissors.jpg");
		//ImageIcon cRock = new ImageIcon("rock2.jpg");
		//ImageIcon cPaper = new ImageIcon("paper2.jpg");
		//ImageIcon cScissors = new ImageIcon("scissors2.jpg");

		//JLabel rockImg = new JLabel("Rock", pRock, JLabel.LEFT);

		//c.add(rockImg);

		pRock = getImage(getCodeBase(), "rock.jpg");
		/*pPaper = getImage(getCodeBase(), "paper.jpg");
		pScissors = getImage(getCodeBase(), "scissors.jpg");
		cRock = getImage(getCodeBase(), "rock2.jpg");
		cPaper = getImage(getCodeBase(), "paper2.jpg");
		cScissors = getImage(getCodeBase(), "scissors2.jpg");*/

	 	/*picLabel = new JLabel();
	 	picLabel2 = new JLabel();
	 	picLabel3 = new JLabel();

	 	comLabel = new JLabel();
	 	comLabel2 = new JLabel();
	 	comLabel3 = new JLabel();

 		picLabel.setIcon( new ImageIcon ("rock.jpg"));
 		picLabel2.setIcon( new ImageIcon ("paper.jpg"));
 		picLabel3.setIcon( new ImageIcon ("scissors.jpg"));

 		comLabel.setIcon( new ImageIcon ("rock2.jpg"));
 		comLabel2.setIcon( new ImageIcon ("paper2.jpg"));
 		comLabel3.setIcon( new ImageIcon ("scissors2.jpg"));


 		picLabel.setBounds(20, 190, 130, 107);
 		picLabel2.setBounds(20, 190, 130, 107);
 		picLabel3.setBounds(20, 190, 130, 107);

 		comLabel.setBounds(340, 190, 130, 107);
 		comLabel2.setBounds(340, 190, 130, 107);
 		comLabel3.setBounds(340, 190, 130, 107);

 		c.add(picLabel);				// add icon label to Panel
 		c.add(picLabel2);				// add icon label to Panel
 		c.add(picLabel3);				// add icon label to Panel
 		c.add(comLabel);				// add icon label to Panel
 		c.add(comLabel2);				// add icon label to Panel
 		c.add(comLabel3);				// add icon label to Panel

 		picLabel.setVisible(false);
 		picLabel2.setVisible(false);
 		picLabel3.setVisible(false);

 		comLabel.setVisible(false);
 		comLabel2.setVisible(false);
 		comLabel3.setVisible(false);*/


		JMenuBar menuBar = new JMenuBar();
		JMenu file = getFileMenu();
		menuBar.add(file);


		setJMenuBar(menuBar);
		//loadImage();

		rockButton = new JButton("Rock");
		scissorsButton = new JButton("Scissors");
		paperButton = new JButton("Paper");
		c.add(rockButton);
		c.add(scissorsButton);
		c.add(paperButton);
		rockButton.addActionListener(this);
		scissorsButton.addActionListener(this);
		paperButton.addActionListener(this);

    }

    public void actionPerformed(ActionEvent event)
    {
		buttonPressed = ((JButton)event.getSource()).getLabel();
		computerValue = randomNumber012();
		translator(buttonPressed);
		repaint();

    }

    public void paint(Graphics g)
    {
    	super.paint(g);
		rockButton.setLocation(20,360);
    	rockButton.setSize(70,35);

    	paperButton.setLocation(210, 360);
    	paperButton.setSize(70, 35);

    	scissorsButton.setLocation(380, 360);
    	scissorsButton.setSize(90, 35);

		computerChoice(g);
		winner(g, computerValue, myValue);

		g.drawString("Player's Wins: " + playerScore, 10, 120);
		g.drawString("Computer's Wins: " + computerScore, 180, 120);
		g.drawString("Draws: " + drawScore, 400, 120);
		g.drawString("Your Choice: " + buttonPressed, 20, 170);
		//g.drawString("Computer's Pick: ", 350, 60);

		g.drawImage(pRock, 20, 190, 130, 107, this);

		g.setColor(Color.blue);
    	g.fillRect (230, 135, 20, 200);

		//g.drawImage(img1, 20, 100, this);

    }

	    int randomNumber012()
	    {
			return (int)(Math.random()*3);
    	}

    public void computerChoice(Graphics g)
    {
		g.drawString("Computer's Pick: ", 350, 170);

		if(computerValue == 0)
		{
		    g.drawString("Computer's Pick: Rock", 350, 170);
		    /*comLabel.setVisible(true);
		    comLabel2.setVisible(false);
		    comLabel3.setVisible(false);*/
		}
		else if(computerValue == 1)
		{
		   	g.drawString("Computer's Pick: Scissors", 350, 170);
		    /*comLabel.setVisible(false);
		    comLabel2.setVisible(false);
		    comLabel3.setVisible(true);*/
		}

		else if(computerValue == 2)
		{
		    g.drawString("Computer's Pick: Paper", 350, 170);
		    /*comLabel.setVisible(false);
		    comLabel2.setVisible(true);
		    comLabel3.setVisible(false);*/
		}

    }


    public void translator(String s)
    {
		if(s.equals("Rock"))
		{
			//Graphics g = getGraphics();
			//g.drawString("Player's Pick: Rock", 70, 60);
		    myValue = 0;
		    /*picLabel.setVisible(true);
		    picLabel2.setVisible(false);
		    picLabel3.setVisible(false);*/
		}
		else if(s.equals("Scissors"))
		{
			Graphics g = getGraphics();
			//g.drawString("Player's Pick: Scissors", 70, 60);
		    myValue = 1;
		    /*picLabel.setVisible(false);
		    picLabel2.setVisible(false);
		    picLabel3.setVisible(true);*/
		}

		else if(s.equals("Paper"))
		{
			//Graphics g = getGraphics();
			//g.drawString("Player's Pick: Paper", 70, 60);
		    myValue = 2;
		    /*picLabel.setVisible(false);
		    picLabel2.setVisible(true);
		    picLabel3.setVisible(false);*/

		}
    }

    public void winner(Graphics g, int cv, int mv)
    {
		if(cv == -1)
		{
		    g.drawString("", 200, 190);
		}

		else if(cv == mv)
		{
		    g.drawString("Draw", 215, 360);
		    drawScore = drawScore + 1;
		}

		else if(cv == 0 && mv == 1 ||
			cv == 2 && mv == 0 ||
			cv == 1 && mv == 2)
		{
		    g.drawString("Computer Wins", 215, 360);
		    computerScore = computerScore + 1;
		}


		else
		{
		    g.drawString("You Win!", 215, 360);
		    playerScore = playerScore + 1;
		}

		if(playerScore == numberOfGames)
    	{
    		JOptionPane.showMessageDialog(null, "Player Wins This Round!\n\n Total Wins for Player: " + (pFinalScore = pFinalScore + 1)
    			 + "\nTotal Wins for Computer: " + cFinalScore);
    		System.out.println("Player Wins This Round!\n\n Total Wins for Player: " + (pFinalScore)
    			 + "\nTotal Wins for Computer: " + cFinalScore);
    		playerScore = 0;
    		computerScore = 0;
    		drawScore = 0;
    	}
    	else if(computerScore == numberOfGames)
    	{
    		JOptionPane.showMessageDialog(null, "Computer Wins This Round!\n\n Total Wins for Player: " + (pFinalScore) + "\n"
    			 + "\nTotal Wins for Computer: " + (cFinalScore = cFinalScore + 1));
    		System.out.println("Computer Wins This Round!\n\n Total Wins for Player: " + (pFinalScore) + "\n"
    			 + "\nTotal Wins for Computer: " + (cFinalScore));
    		playerScore = 0;
    		computerScore = 0;
    		drawScore = 0;
     	}
    }
    public JMenu getFileMenu()
 	{
      JMenu myMenu = new JMenu("Options");

      JMenuItem checkScoreItem = new JMenuItem("Check the current score");
      myMenu.add(checkScoreItem);
      checkScoreItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                JOptionPane.showMessageDialog(null, "Current Scores\n\n Total Wins for Player: " + (pFinalScore) + "\n"
    			 + "\nTotal Wins for Computer: " + (cFinalScore));

    			 System.out.println("Current Scores:\n\n Total Wins for Player: " + (pFinalScore) + "\n"
    			 + "\nTotal Wins for Computer: " + (cFinalScore));
            }

        });

        JMenuItem setGame = new JMenuItem("Number of Games");
        myMenu.add(setGame);
        setGame.addActionListener(new ActionListener(){
       		public void actionPerformed(ActionEvent event){
				String input = JOptionPane.showInputDialog(null, "How many games would you like to make it out of");
				int games = Integer.parseInt(input);
				numberOfGames = games;
				JOptionPane.showMessageDialog(null, "This game will be out of " + games + " for all of your current games");
      		}

        });

        JMenuItem resetScoreItem = new JMenuItem("Reset your scores");
       	myMenu.add(resetScoreItem);
       	resetScoreItem.addActionListener(new ActionListener(){
       		public void actionPerformed(ActionEvent event){
       			int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to reset your scores?", "Confirm",
       		    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    			if (response == JOptionPane.NO_OPTION)
    			{
      				System.out.println("No button clicked");
    			}
    			else if (response == JOptionPane.YES_OPTION)
    			{
      				System.out.println("Yes button clicked");

      				JOptionPane.showMessageDialog(null, "Scores have been reseted to 0.");
       				pFinalScore = 0;
       				cFinalScore = 0;
       				playerScore = 0;
       				computerScore = 0;
       				drawScore = 0;

			 		/*picLabel.setVisible(false);
			 		picLabel2.setVisible(false);
			 		picLabel3.setVisible(false);

			 		comLabel.setVisible(false);
			 		comLabel2.setVisible(false);
			 		comLabel3.setVisible(false);*/

       				System.out.println("Scores have been reseted to 0");
    			}

    			else if (response == JOptionPane.CLOSED_OPTION)
    			{
      				System.out.println("Reset Score confirmation box is closed");
    			}

       		}
       	});

      return myMenu;
   }

}

At first, I've tried doing JLabel into ImageIcon and when I run it, it works perfectly fine, but when I run it on a web browser, the program never shows up. I've tried Firefox, Chrome, and IE and none of them works, However, when I added for example, "Image pRock" as well as instantiating it to getImagefile to getCodeBase, I added the g.drawImage in the paint method and that works correctly (Both when running it to JCreator and to my web browsers). Now the only problem is to make these images to appear and disappear and this is where I'm having some issues. I've tried doing Google search, but they're all talking mostly on Applets with images. Can anyone help me on this please? I did wrote a lot about this and I apologize for this, but I definitely need to know as to how I can do this to get a better understanding of JApplets. I hope you understand what I'm saying and if you want me to clarify, please let me know. Thanks.

Dani AI

Generated

Short version: stop drawing directly with getGraphics() and stop hard-coding a single image in paint(); either (A) keep custom painting but draw the correct image inside a Swing paintComponent(...) using your myValue/computerValue, or (B) use Swing components (two JLabels—one for the player, one for the computer) and swap their ImageIcons. Swing expects UI changes on the Event Dispatch Thread and painting to happen in the paint chain, not from ad-hoc Graphics objects. (See the Java tutorials on custom painting and Swing threading.)
(https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) (https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html)

Practical, minimal approach (preferred): create two JLabels, load icons from the classpath with getResource(...) and call label.setIcon(...) to show or label.setIcon(null) to hide. Loading with getResource/ImageIcon(URL) avoids the “works locally, fails in browser” problem when images aren’t packaged with the app. See “How to Use Icons” for an example factory that returns new ImageIcon(getClass().getResource(path)). (https://docs.oracle.com/javase/tutorial/uiswing/components/icon.html)

About ’s remove() idea: remove() will work, but after adding/removing components you must call revalidate() and repaint() so Swing relayouts and repaints the container. Often it’s simpler and faster to swap an icon (or call setVisible(false) on a JLabel) rather than remove/add components repeatedly. (https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/swing002.html)

One more crucial note for future readers: browser-based JApplets are effectively obsolete — the Applet API was deprecated for removal and major browsers removed NPAPI plugin support, so running a JApplet in modern desktop browsers is unlikely to work. If the goal is web deployment, consider converting the UI to a desktop Swing app, Java Web Start alternatives, or an HTML5/JavaScript front end. (https://openjdk.org/jeps/398) (https://chromium.org/developers/npapi-deprecation)

Troubleshooting checklist: 1) stop using getGraphics(); 2) move painting to paintComponent or use JLabels; 3) load images via getResource/ImageIcon; 4) update UI on the EDT; 5) call revalidate()+repaint() after structural changes. This will make the rock/paper/scissors icons reliably appear and disappear.

I'm fairly sure the remove() method would work.

Member Avatar for Member #413109

I'm fairly sure the remove() method would work.

Sorry for the late reply, but how would I use the remove() method in there? How would I make the image to appear again if either the rock. paper, or scissors button to be pressed again? Please let me know. Thanks!

I THINK that method will work with your image objects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.