Я работаю над этим RPSGUI; все работает, насколько логично, но я перешел на заключительную стадию около недели назад, и с тех пор я застрял здесь. Я не могу обновить свои ярлыки. Так скажите, что пользователь выиграл, счетчик будет идти от 0 до 1, 2 и т. Д. У меня много чего прокомментировано, поэтому вы можете видеть, что я пробовал. Я фактически удалил несколько частей того, что я комментировал, потому что я путался, но да. Я также хотел бы, чтобы gui сказал, что было сыграно, и я не уверен, с чего начать с этого: - /. Я надеюсь, что кто-то сможет мне помочь. Это значило бы для меня много.Ярлык не обновляется потоком
Это программа без класса драйвера. Ничего не стоит в классе драйвера, чтобы отобразить его.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class GamePanel extends JPanel{
private JButton rockButton, paperButton, scissorsButton;
private JLabel userLabel, computerLabel, resultLabel, winLabel, tieLabel, loseLabel;
private int winInt, tieInt, loseInt = 0;
private String rockButtonText = "Rock";
private String paperButtonText = "Paper";
private String scissorsButtonText = "Scissors";
private JPanel buttonPanel, labelPanel, resultPanel;
public int computerInt;
String[] attackArray = {"Rock", "Paper", "Scissors"};
public GamePanel(){
String[] attackArray = {"Rock", "Paper", "Scissors"};
setLayout(new GridLayout(5,3));
setBackground(Color.white.brighter());
setForeground(Color.ORANGE.darker());
//make the buttons
JButton rockButton = new JButton(rockButtonText);
JButton paperButton = new JButton(paperButtonText);
JButton scissorsButton = new JButton(scissorsButtonText);
//style the buttons
rockButton.setBackground(Color.orange);
rockButton.setForeground(Color.black.darker());
paperButton.setBackground(Color.orange);
paperButton.setForeground(Color.black.darker());
scissorsButton.setBackground(Color.orange);
scissorsButton.setForeground(Color.black.darker());
//add labels
JLabel userLabel = new JLabel("User:");
JLabel computerLabel = new JLabel("Computer:");
JLabel winLabel = new JLabel("Win: " + winInt);
JLabel tieLabel = new JLabel("Tie: " + tieInt);
JLabel loseLabel = new JLabel("Lose:" + loseInt);
//style Labels
userLabel.setBackground(Color.orange);
userLabel.setForeground(Color.black.darker());
computerLabel.setBackground(Color.orange);
computerLabel.setForeground(Color.black.darker());
winLabel.setBackground(Color.orange);
winLabel.setForeground(Color.black.darker());
tieLabel.setBackground(Color.orange);
tieLabel.setForeground(Color.black.darker());
loseLabel.setBackground(Color.orange);
loseLabel.setForeground(Color.black.darker());
//add buttons to panel
add(rockButton);
//add(Box.createRigidArea(new Dimension (0,10)));
add(paperButton);
//add(Box.createRigidArea(new Dimension (0,10)));
add(scissorsButton);
//add(Box.createRigidArea(new Dimension (0,10)));
add(userLabel);
//add(Box.createRigidArea(new Dimension (0,10)));
add(computerLabel);
//add(Box.createRigidArea(new Dimension (0,10)));
add(winLabel);
//add(Box.createRigidArea(new Dimension (0,10)));
add(tieLabel);
//add(Box.createRigidArea(new Dimension (0,10)));
add(loseLabel);
//add(Box.createRigidArea(new Dimension (0,10)));
// add action listeners
rockButton.addActionListener(new ButtonListener());
paperButton.addActionListener(new ButtonListener());
scissorsButton.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae){
int computerSourceAI = (int) (Math.random() * 2); //random generator
String oppChoice = attackArray[computerSourceAI]; // the choice of your opponent
String yourChoice = ((JButton) ae.getSource()).getText(); // casts source from object to button and gets the text
int outcome = determineWinner(yourChoice, oppChoice);
// 0 = tie
//1 == win
//2 = lose
if (outcome == 1)
{
// win message
//System.out.println("You win!");
winLabel.setText("You Won" + winInt++);
}
else if (outcome == 0)
{
// tie message
//System.out.println("Tie");
tieLabel.setText("You tied" + tieInt++);
}
else
{
loseLabel.setText("You lose" + loseInt++);
}
}
}
public int determineWinner(String you, String opponent)
{
if(you.equals("Rock") && (opponent.equals("Rock"))){
//tieInt++;
tieLabel.setText("You tied" + tieInt++);
return tieInt++;
}else if(you.equals("Rock") && (opponent.equals("Rock"))){
//tieInt++;
tieLabel.setText("You tied" + tieInt++);
return tieInt++;
}else if(you.equals("Scissors") && (opponent.equals("Scissors"))){
//tieInt++;
tieLabel.setText("You tied" + tieInt++);
return tieInt++;
}else if(you.equals("Rock") && (opponent.equals("Scissors"))){
//winInt++;
winLabel.setText("You Won" + winInt++);
return winInt++;
}else if(you.equals("Paper") && (opponent.equals("Rock"))){
//winInt++;
//return 1;
winLabel.setText("You Won" + winInt++);
return winInt++;
}else if(you.equals("Scissors") && (opponent.equals("Paper"))){
//winInt++;
//return 1;
winLabel.setText("You Won" + winInt++);
return winInt++;
}else if(you.equals("Scissors") && (opponent.equals("Rock"))){
//loseInt++;
//return -1;
loseLabel.setText("You lose" + loseInt++);
return loseInt++;
}else if(you.equals("Rock") && (opponent.equals("Paper"))){
//loseInt++;
//return -1;
loseLabel.setText("You lose" + loseInt++);
return loseInt++;
}else
if(you.equals("Paper") && (opponent.equals("Scissors"))){
//loseInt++;
//return -1;
loseLabel.setText("You lose" + loseInt++);
return loseInt++;
}
return 0;
}
Это имеет смысл, но оно все еще не работает: - /. Это ошибка, которую я получаю Исключение в потоке «AWT-EventQueue-0» java.lang.NullPointerException \t в GamePanel.determineWinner (GamePanel.java:176), и он продолжается, как этот javax.swing.AbstractButton $ Handler.actionPerformed (Неизвестно Источник) \t at javax.swing.DefaultButtonModel.fireActionPerformed (Неизвестный источник) – wwe9112
Подождите, пока он работает. Но он не показывает, кто играл то, что рядом с пользователем и компьютером с «вы выиграли» или «вы потеряли» тип вещи :( – wwe9112
@ wwe9112: время для некоторой отладки. Либо пользователь может отлаживать свои возможности IDE, либо использовать кучу операторов println, чтобы выяснить, в каком состоянии находятся ваши переменные в качестве программы, и тем самым найти нашу ошибку. –