I am currently working on a rock papper scissors game. Very early into the coding I have encountered an issue when I can't get the code to repaint something new when a button is pressed despite ofcourse the button is working and registered by the code. The buttons do work as it does printout what is being pressed and also the value of y also changes so the code works somewhat, but it is not doing it properly.
public class RockPaperScissors implements ActionListener {
JButton rock =new JButton("Select rock");
JButton paper =new JButton("Select paper");
JButton scissors =new JButton("Select scissors");
public void frame() {
Gui gui = new Gui();
JFrame b = new JFrame("Rock paper scissors");
rock.setBounds(150,100,120,30);
paper.setBounds(350,100,120,30);
scissors.setBounds(550,100,120,30);
b.setSize(905,705);
b.setLocation(300,60);
b.setResizable(false);
b.setVisible(true);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setResizable(false);
b.setVisible(true);
b.add(rock);
b.add(paper);
b.add(scissors);
rock.addActionListener(this);
paper.addActionListener(this);
scissors.addActionListener(this);
b.add(gui);
}
public static void main(String[] args) {
RockPaperScissors start = new RockPaperScissors();
start.frame();
}
@Override
public void actionPerformed(ActionEvent e) {
Gui selection = new Gui();
if (e.getSource() == rock){
selection.selector("rock");
} else if (e.getSource() == paper) {
selection.selector("paper");
} else if (e.getSource() == scissors) {
selection.selector("scissors");
}
}
And this is the Gui class meant to of course handle the gui right now task is just to draw over different coloured squares when the correct button is pressed, but nothing happens, I suspect it might be an obvious solution I am missing.
public class Gui extends JPanel {
private int y;
public void paint(Graphics g) {
g.setColor(Color.white);
g.fillRect(50, 300, 300, 300);
g.setColor(Color.white);
g.fillRect(550, 300, 300, 300);
if (y == 1) {
g.setColor(Color.blue);
g.fillRect(50, 300, 300, 300);
}
if (y == 2) {
g.setColor(Color.black);
g.fillRect(50, 300, 300, 300);
}
if (y == 3) {
g.setColor(Color.yellow);
g.fillRect(50, 300, 300, 300);
}
}
public void selector(String x){
if (x == "paper"){
y = 1;
repaint();
System.out.println("paper" + y);
} else if (x == "rock") {
y = 2;
repaint();
System.out.println("rock" + y);
} else if (x == "scissors") {
y = 3;
repaint();
System.out.println("scissors" + y);
}
}
}