Louis B
Louis B

Reputation: 342

Trying to create a simple applet but it won't run through the whole program

I'm creating an applet and all that happens is it opens displays "How many genres are there?" and then a textField appears. i enter a number and hit enter but nothing ever happens! (i dont get any errors but nothing happens)

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class appletPracticw extends Applet implements ActionListener { 
TextField numG;
TextField g ;
TextField numS; 
TextField sog; 
private int number;
private int numberOfSongs;
String gener;
String songName;
public void go(){
    numG= new TextField(5);
    numS= new TextField(5);
    g= new TextField(5);
    sog= new TextField(5);
    numG.addActionListener(this);
    g.addActionListener(this);
    sog.addActionListener(this);
    numS.addActionListener(this);
    Tracker t=new Tracker();
    add(new Label("How many genres are there? "));  add(numG);
    for(int i=0;i<number;i++){
        catogories c=new catogories();
        add(new Label("Name of genere: "));  add(g);
        t.addCatogory(c,gener);
    }
    for(int x=0;x<number;x++){
        add(new Label("How many songs are there in "+t.getCatogories().get(x).getGenere()));  add(numS);
        for(int i=0;i<numberOfSongs;i++){
            Songs s=new Songs();
            add(new Label("The name of song "+(i+1)+" is"));  add(sog);
            t.getCatogories().get(x).addSong(s, songName);
        }
    }
}
public void actionPerformed(ActionEvent e) {
    if(e.getSource()==numG){
        String num=numG.getText();
        number=Integer.parseInt(num);
    }
    if(e.getSource()==numS){
        String num=numS.getText();
        numberOfSongs=Integer.parseInt(num);
    }
    if(e.getSource()==g){
        gener=g.getText();
    }
    if(e.getSource()==sog){
        songName=sog.getText();
    }
}
public void init() {
    go();

} public appletPracticw() {

} }

Upvotes: 0

Views: 122

Answers (1)

Sky
Sky

Reputation: 709

The field number is initialized with the value 0.

You build the applet, adding labels and text fields. It looks like you are assuming that the program waits for a user input at this line:

add(new Label("How many genres are there? "));  add(numG);

In reality it is just creating the user interface and doesn't wait for inputs.

So the two for loops are executed, but as number is still 0, the loops are never entered.

What you should do instead is perform the actual action (in your case this is changing the GUI by adding new labels and fields) in the actionPerformed method, so that category labels and input fields are created after the user has entered the number of genres. The same must be done for the second loop, too.

Upvotes: 2

Related Questions