Presh_K7 Presh_K7 - 1 year ago 76
Java Question

How to get conditionally assigned value from another class

I'm having some issues on using a conditionally assigned value in more than one class. I want to apply the use of a value in one class if and only if a condition is met, then use it in some-other class to add up to a total score. this is my code!

public class Beginner extends JPanel {

static JButton quest;
Random rand = new Random();

int n = 10;

static List <Point> points = new ArrayList<Point> ();

int scores;
int fails;

public Beginner() {

int radius = 200;
Point center = new Point (250, 250);

double angle = Math.toRadians(360 / n);


for (int i = 0; i < n; i++) {
double theta = i * angle;

int dx = (int) (radius * Math.sin(theta));

int dy = (int) (radius * Math.cos(theta));

Point p = new Point (center.x + dx , center.y + dy);



draw (points);

public void draw (List<Point> points) {

JPanel panels = new JPanel();

SpringLayout spring = new SpringLayout();

int count = 1;
for (Point point: points) {

quest = new JButton("Question " + count);
Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);

add (quest);

spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );

spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );




quest.addActionListener(new java.awt.event.ActionListener(){
public void actionPerformed (ActionEvent p) {

if (point.equals(points.get(0))) {

new Quest1();

JButton source = (JButton) p.getSource();

else if (point.equals(points.get(1))) {

new Quest2();

JButton source = (JButton) p.getSource();
else if (point.equals(points.get(2))) {

new Quest3();

JButton source = (JButton) p.getSource();

else if (point.equals(points.get(3))) {

new Quest4();

JButton source = (JButton) p.getSource();

else if (point.equals(points.get(4))) {

new Quest5();

JButton source = (JButton) p.getSource();

Now, this is what my first called-up class (named Quest1) looks like

public class Quest1 {
//sound files to be shuffled and played!
String [] word = { "C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/audio.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/bomb.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/baby.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/gym.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/hearing.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/goal.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/manifest.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/mountain.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/market.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/debate.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/election.wav",
"C:/Users/HP/Workspace/spellingApp/src/Level1/Question 1/number.wav",
//matching strings for each file
String [] words = { "Audio", "Bomb", "Baby", "Gym", "Hearing", "Goal", "Manifest","Mountain", "Market", "Debate", "Election", "Number" };

Random rand = new Random();
int random = rand.nextInt(word.length);
String temp = word[random];

int scores;
int fails;

public Quest1 () {

//announcing the JComponents to be used
JFrame frame = new JFrame ();
JButton click = new JButton("Play");
JTextField type = new JTextField(15);
JLabel pic = new JLabel(new ImageIcon("C:\\Users\\HP\\Desktop\\Sample pics\\1.png"));
JButton score = new JButton ("Check My Answer");
JPanel cont = new JPanel ();

//set up frame properties
frame.setLayout(new FlowLayout());
frame.add(cont, BorderLayout.CENTER);

//setting layout of JPanel
cont.setLayout(new GridBagLayout());
cont.setPreferredSize(new Dimension(500,500));
cont.setLocation(100, 50);
GridBagConstraints g = new GridBagConstraints();
g.anchor = GridBagConstraints.WEST;
g.gridx = 4;
g.gridy = 2;
g.gridwidth = 2;
g.insets = new Insets (70, 2, 2, 2);
cont.add(pic , g);

g.anchor = GridBagConstraints.WEST;
g.gridx = 4;
g.gridy = 5;
g.gridwidth = 2;
g.insets = new Insets (50, 2, 2, 2);
cont.add(click, g);

click.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {
//sound file shuffled and played
g.anchor = GridBagConstraints.EAST;
g.gridx = 10;
g.gridy = 4;
g.gridwidth = 5;
g.insets = new Insets(30, 2, 2, 10);
Font fonty = new Font("Lucida", Font.PLAIN, 15);
cont.add(type, g);

g.anchor = GridBagConstraints.SOUTH;
g.gridx = 9;
g.gridy = 8;
g.gridwidth = 2;
g.insets = new Insets(2, 2, 2, 50);
cont.add(score, g);

score.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent tx) {

if (type.getText().equals(words[random])) {

//sound file played
scores+= 3;
String a = "Correct!..... The answer is " + words[random];
JOptionPane.showMessageDialog(null, a);


else {
//sound file played again
// This is where my problem is: The other 10 classes are like
//this, I want to get this value and that of scores (depending on the
//condition that is met), and add them up in the class beginner! )
String a = "Sorry, The Answer is " + words[random];
JOptionPane.showMessageDialog(null, a);

//sound file played


Answer Source

Your score and fail are local variables within the listener event. If you create an instance variable in your help class you can update them within the listener but they will persist as long as your program is running and then can be passed into more classes as constructor parameter for whatever purpose you may need.

public class help extends JFrame {
        JPanel hold = new JPanel ();
        JTextField enter = new JTextField(10);
        JButton check = new JButton ("Check answer");
        JButton quest = new JButton ("See question");
        JLabel lunch = new JLabel ("Who is the current President of the United States?");

        //Add fields you want to track here
        int scores;
        int fails;

     public help () {

Then inside your listeners

     scores += 3; //track them anyway you want


So it looks like you want to pass the score/fails from your Quest class back to your original class. You can do this by adding some accessor methods for scores and fails to your Quest class.

public int getScores(){ 
       return scores;

public int getFails(){
       return fails;

This will allow you get retrieve the values when you need them. You'd simply call them on the Quest object you made. However there's another problem...

new Quest1(); 

The quest needs to be stored in a variable like scores and fails or else it will get thrown away by the garbage collector. Add a variable that will hold the current Quest on top then swap them out when you switch quests.

Quest1 q1;
q1 = new Quest1();
scores = q1.getScores();
fails = q1.getFails();

Update: Button Flags

You can add flags to check if things have occurred by adding booleans variables. In this case you can have Quest1-5 flags in your Beginner class. When the user clicks on the class you can change it to true, then check if all of them have been done.

boolean Q1 = false;
boolean Q2 = false;

if (point.equals(points.get(0))) { // User clicks quest 1
    Q1 = true;

if (checkQuests()){
    //do stuff if all buttons are clicked


public boolean checkQuests(){ //cleaner if you use arrays
   if(Q1 == false || Q2 == false || ... Q5== false){
      return false;
      return true;

Update: Call back function

When working GUIs and listeners, not all actions happen in the sequence you want it to. GUIs and events happen on their own thread and often you want to trigger an event at the end of another. You can do this by utilize a call back function.

What is a callback function?

Here's how you can implement one in your program.

Inside your Quests include an interface and variable for an interface:

public class Quest{

    Callback cb;

    interface Callback{
        public void callBack();

    //add some way to set the call back, such as setter (or use constructor)
    public setCB(Callback cb){ this.cb = cb;}

  //Inside the action listener of your quest doing something
    cb.callback(); //call the callback method when you are done and want to do your check (it calls the beginner class back)

Inside your Beginner class:

//When creating a quest 
  Q1 = new Quest1();
  Q1.setCB(new CallBack{
      public void callBack(){
          CheckQuests(); //this tells the program what to do when it hears back from Q1

What ends up happening is when the code of Q1 finishes, it calls the callBack() method (it could be any time but in your case call it when you're done with your logic).

The beginner class passes in code that tells Q1 what it should do when that method is called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download