Reputation: 93
I am currently learning about GUI development in Java, and I am supposed to make a rock, paper, scissor game. So far I've made the GUI itself (an ugly one, but still a GUI), but I don't know how to "connect" the selection you make into if's and else's. This is what I have so far:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Oppgave extends JFrame implements ActionListener{
public JLabel title;
public JButton button;
public JList liste;
public JList liste2;
public Oppgave(){
super("A game");
setLayout(new BorderLayout());
title = new JLabel("Rock, scissor, paper!");
add(title, BorderLayout.NORTH);
title.setHorizontalAlignment(SwingConstants.CENTER);
String[] choice = {"Rock","scissor","paper"};
liste = new JList(choice);
liste.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
add(liste, BorderLayout.WEST);
liste2 = new JList(choice);
liste2.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);
add(liste2, BorderLayout.EAST);
button = new JButton("Play");
add(button, BorderLayout.SOUTH);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(button)){
JOptionPane.showMessageDialog(null, "Player 1 chose: "+liste.getSelectedValue());
JOptionPane.showMessageDialog(null, "Player 2 chose: "+liste2.getSelectedValue());
}
}
}
So now I want to make if's and else's, like if player 1 picks rock, then check what player 2 picks and display the winner.
How do I use the selections from the JLists in if/else statements?
Upvotes: 0
Views: 3089
Reputation: 1542
So you have the output and don't know what to do? Example code you may want to use:
String p1 = "";
String p2 = "";
if(liste1.getSelectedValue().equals("rock"))
{
p1 = "rock";
}
if(liste1.getSelectedValue().equals("paper"))
{
p1 = "paper";
}
if(liste1.getSelectedValue().equals("scissors"))
{
p1 = "scissors";
}
repeat for player 2, using a string called p2. Then:
Boolean player2win = false;
Boolean player1win = false;
Boolean tie = false;
if(p1.equals(p2))
{
tie = true;
}
if(p1.equals("rock") && p2.equals("scissors"))
{
player1win = true;
}
if(p1.equals("paper") && p2.equals("rock"))
{
player1win = true;
}
if(p1.equals("scissors") && p2.equals("paper"))
{
player1win = true;
}
else
{
player2win = true;
}
That should work
Upvotes: 2
Reputation: 6249
Here's my understanding of what you should attempt to do:
String player1Choice = liste.getSelectedValue()
String player2Choice = liste2.getSelectedValue()
if (player1Choice.equals(player2Choice)
System.out.println("Draw"); // Or whatever you want to output to, could be another jLabel
else if(player1Choice.equals(rock) && player2Choice.equals(paper))
System.out.println("Player 2 wins.");
// And just keep adding on here.....
Upvotes: 3