Liam Hait
Liam Hait

Reputation: 11

Trying to start program on JButton press

I am trying to make a simple program that will ask the user a question and then compare their answer with a stored correct answer. The problem seems to be that the main loop of the program is not running when I click the Ready JButton.

I tried changing the main method to another non-default name and adding a call to it in the actionPerformed() method, and it did seem to execute the loop at least once, but then led to not being able to close the applet without the task manager once I clicked the button. I don't know if that means it hit an endless loop or what.

I'm sure there is more to fix in this code besides this issue, but I cannot make any progress on that without clearing this up first. If there is a problem with the way I went about creating the GUI please let me know. I tried to base it off of an assignment I did that worked just fine, so I don't know whether or not that is the issue.

Any help provided is appreciated.

Here is the code:

import java.awt.*;
import javax.swing.*;

public class Langarden_App extends JApplet{
    private int width = 800, height = 600;
    private LangardenPanel langPanel;

    public void init(){
        langPanel = new LangardenPanel();
        getContentPane().add(langPanel);
        setSize(width, height);
    }
}

And the class with the logic

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.*;

public class LangardenPanel extends JPanel{

    private static JButton submit;
    private static JButton ready = new JButton("Ready");
    private static JLabel instruct;
    private JTextField input = new JTextField(100);
    private static String inString;
    private static ArrayList<String> questions;
    private static ArrayList<String> answers;
    private static Random rand = new Random();

    public LangardenPanel(){
        questions = new ArrayList<String> (Arrays.asList("¿Qué es la palabra para 'inveirno' en ingles?", "¿Qué es la forma de 'yo' del verbo 'venir'?"));
        answers = new ArrayList<String> (Arrays.asList("winter", "voy"));
        instruct = new JLabel("Welcome to Langarden! Press Submit to begin. You have one minute and three attempts for each question.");
        submit = new JButton("Submit");
        this.setLayout(new BorderLayout());
        add(BorderLayout.SOUTH, ready);
        add(BorderLayout.NORTH, instruct);
        add(BorderLayout.CENTER, input);
        ready.addActionListener(new SubListener());
    }

    public static void main(String[] args){
        try{
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e){
        }
        System.out.println("Setting text");
        instruct.setText("Alright! Let's Go!");
        try{
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e){
        }
        do{
            System.out.println("Running loop");
            int qnum = rand.nextInt(questions.size());
            instruct.setText(questions.get(qnum));
            for (int i=0; i<3; i++){
                try {
                    TimeUnit.SECONDS.sleep(60);
                } catch (InterruptedException e) {
                }
                if(checkAnswer(qnum, inString)){
                    instruct.setText("Correct!");
                    break;
                } else {
                    instruct.setText("Try again...\n" + questions.get(qnum));
                }
            }
            instruct.setText("The correct answer was " + answers.get(qnum));
            try{
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e){
            }
            questions.remove(qnum);
            answers.remove(qnum);
            instruct.setText("Would you like to continue? Enter No and click Submit to exit.");
        } while (!inString.equalsIgnoreCase("No") && questions.size() != 0);
        instruct.setText("Congratulations, you have completed this module!");
    }

    private static boolean checkAnswer(int qnum, String inString) {
        if (answers.get(qnum).equalsIgnoreCase(inString))
            return true;
        return false;
    }

    private class SubListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            System.out.println("Button Pressed!");
            if(e.getSource() == ready){
                add(BorderLayout.SOUTH, submit);
                submit.addActionListener(new SubListener());
            } else {
                inString = input.getText();
            }
        }
    }
}

Upvotes: 1

Views: 32

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

  1. Get rid of the main method. If this is running as an applet, then the program has no business having a main method.
  2. Make all fields non-static. Yes all.
  3. Get rid of the while-true loop. If this runs, this will squelch your Swing event thread rendering your GUI frozen and helpless. Use a Swing Timer instead as a "pseudo" loop. Please check out the Swing Timer Tutorial for more on this.
  4. Any time you add a component to a container, you should call revalidate() and repaint() on that same container so that the container's layout managers can layout the new component, and so that the OS can repaint over any "dirty" pixels.
  5. Rather than add a new JButton as you're doing, much better is to swap components using a CardLayout. The tutorial can be found here: CardLayout tutorial.

Upvotes: 2

Related Questions