Home > Back-end >  Java "press button" with different actions each time pressed
Java "press button" with different actions each time pressed

Time:09-17

I would like to program a small score counter. I have implemented two buttons that only return one thing when pressed. I want a new score to appear every time is pressed.

The following shows the code I already written:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class MyFrame extends JFrame implements ActionListener{
    
    
    JButton button;
    JButton button2;
    
    int clicked1Count = 0;
    int clicked2Count = 0;
    
    
    
Thank you in advance.

CodePudding user response:

You could make 2 variables as in

clicked1Count = 0
clicked2Count = 0

And in your action performed increase the counter as per your need. And print it after that

if (ae.getSource()==button){
    clicked1Count  ;
}
else if (ae.getSource()==button2) {
    clicked2Count  ;
}

CodePudding user response:

Your problem is that your underlying design is basically nonexistent. If you don't spend considerable time to think upfront how to model the things you want to work with, you will always end up with overly complicated spaghetti code.

As in:

  • put the "amount to increment" into an array. Then your clickCount is used as index in that array.
  • go with one listener per button.
  • instead of working with raw int values that hold your values, introduce a class like Player that has a setScore method. Or even more OOP: the player class gets a method increaseScore(). And that method isolates the knowledge how the score gets increased.

In other words: create helpful abstractions. That is what makes up good OOP. Instead of trying to stuff all code for everything into one action listener.

  • Related