Java GUI:Rock,剪刀纸游戏

时间:2012-10-08 16:43:00

标签: java user-interface if-statement jlist

我目前正在学习Java中的GUI开发,我应该做一个摇滚,纸张,剪刀游戏。到目前为止,我已经制作了GUI本身(一个丑陋的GUI,但仍然是一个GUI),但我不知道如何将你所做的选择“连接”成if if和else。这就是我到目前为止所做的:

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());
    }

    }
}

所以现在我想制作if's and else's,就像玩家1选择摇滚一样,然后检查玩家2选择并显示获胜者。

如何在if / else语句中使用JLists中的选择?

2 个答案:

答案 0 :(得分:3)

以下是我对你应该尝试做什么的理解:

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.....

答案 1 :(得分:2)

所以你有输出但不知道该怎么办? 您可能想要使用的示例代码:

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";
}

使用名为p2的字符串重复播放器2。然后:

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;
}

那应该有用