10 Replies - 1988 Views - Last Post: 10 May 2011 - 05:49 PM Rate Topic: -----

#1 Tflaga   User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 44
  • Joined: 16-April 11

Java Question on actionlistener(actionevent)

Posted 04 May 2011 - 07:40 PM

Im working on a hangman code. I originally have all in one class but I need to make it where I can create a separate class for the actionlistener(actionevent) method. I did make the class but now the game doesn't work right. When I go to guess a letter nothing happens. Thanks for any feedback. The first class below is the actionlistener class. Also how can i change it to extend JFrame instead of Applet in the main(second) class I provided below?

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

public class HangmanListener extends hangman implements ActionListener {


public Button Enter;
public TextField Letter;


public HangmanListener(Button B)/>{
Enter = b;

}

public void actionPerformed(ActionEvent e){
Button b = (Button)e.getSource();
if (e.getSource() == B)/>{
processTurn();

Letter.setText("");
repaint();
}
}
}




this is the main(second class)....the code below is shortened a little to save space. Im just showing the important code.

public class hangman extends Applet {//implements ActionListener {

static final int hung = 11;
public int errors;
public String message;
public String information;
public String rword;
public StringBuffer gword;
public Button Enter;
public TextField Letter;
Image background;



public void init() {

background = getImage(getCodeBase(),"nightsky.png");

Letter = new TextField();

Enter = new Button("Enter");
//HangmanListener listener = new HangmanListener(Enter);

add(new Label("Pick a letter:"));
add(Letter);
add(Enter);

// Enter.addActionListener(listener);

createGame();
}

public void createGame(){

errors = 0;

String str = "school|java|programming|science|compute…
String[] temp;

String delimiter = "\\|";

temp = str.split(delimiter);

Random randomGenerator = new Random();


int randomInt = randomGenerator.nextInt(temp.length);

rword = new String(temp[randomInt]);

char positions[] = new char[rword.length()];
for (int i = 0; i < rword.length(); i++) {
positions[i] = '-';

}
String s = new String(positions);
gword = new StringBuffer(s);

Letter.setText("");

message="";
information = "";
repaint();
}



public void paint(Graphics g) {
super.paint(g);
g.drawImage(background, 0, 156, Color.green, Enter);


int baseY = 350;
g.setColor(Color.lightGray);
g.drawRect(0, baseY,400,baseY);
g.fillRect(0, baseY,400,baseY);

g.setColor(Color.darkGray);
//g.drawRect(250,50,125,50);
//g.fillRect(250,50,125,50);

if (errors > 0){
g.drawLine(125,baseY,125,baseY-100);
g.drawLine(123,baseY,123,baseY-100);
}
if(ect.....................)

g.drawString( message, 60, baseY+25 );
g.drawString( information, 25, baseY+45 );
g.drawString( new String (gword), 110, 60);

}
public void listener() {

HangmanListener listener = new HangmanListener(Enter);
Enter.addActionListener(listener);
}

protected void processTurn(){
String s, t;
char a;

s = Letter.getText();
a = s.charAt(0);

if (!Character.isLetter(a)){
message="Letters only";
return;
}
if (s.length()>1){
message="Enter 1 letter only";
return;
}

t = new String(gword);
if (t.indexOf(s) != -1){
JOptionPane.showMessageDialog(null, "LETTER USED ALREADY");

return;
}

if (rword.indexOf(s) == -1){
message="";
errors++;
if (errors == hung){
JOptionPane.showMessageDialog(null, "YOU LOST!");

}

return;
}

for (int i = 0; i < rword.length(); i++){
if (rword.charAt(i) == a){
gword.setCharAt(i, a);
}
}
t = new String(gword);


if (t.indexOf('-') == -1){
JOptionPane.showMessageDialog(null, "YOU WIN!");
return;
}

message="";
repaint();
}

}



Is This A Good Question/Topic? 0
  • +

Replies To: Java Question on actionlistener(actionevent)

#2 exiles.prx   User is offline

  • D.I.C Head

Reputation: 65
  • View blog
  • Posts: 241
  • Joined: 22-November 10

Re: Java Question on actionlistener(actionevent)

Posted 04 May 2011 - 08:35 PM

In your main class you created the method public void listener() to setup your action listener, but I don't see you calling it anywhere. As far as changing the main class Hangman from a JApplet to a JFrame, a JApplet requires the method public void init() and a java application does not. You will need the method public static void main(String[] ags) either in your main class or another class to run your application.
Was This Post Helpful? 0
  • +
  • -

#3 Tflaga   User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 44
  • Joined: 16-April 11

Re: Java Question on actionlistener(actionevent)

Posted 04 May 2011 - 08:51 PM

View Postexiles.prx, on 04 May 2011 - 08:35 PM, said:

In your main class you created the method public void listener() to setup your action listener, but I don't see you calling it anywhere. As far as changing the main class Hangman from a JApplet to a JFrame, a JApplet requires the method public void init() and a java application does not. You will need the method public static void main(String[] ags) either in your main class or another class to run your application.



Thanks for the feedback. You are right i do need to call the method but when ever and where ever call it i start getting a null pointer exception. Any guesses?
Was This Post Helpful? 0
  • +
  • -

#4 exiles.prx   User is offline

  • D.I.C Head

Reputation: 65
  • View blog
  • Posts: 241
  • Joined: 22-November 10

Re: Java Question on actionlistener(actionevent)

Posted 04 May 2011 - 09:11 PM

If your calling your listener method before your button gets initialized, you will get that error. Also java is case sensitive, so B is not the same as b. I see them being uses interchangeably in your code a couple times. Could be another reason.
Was This Post Helpful? 0
  • +
  • -

#5 pbl   User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8381
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Java Question on actionlistener(actionevent)

Posted 05 May 2011 - 04:42 AM

View Postexiles.prx, on 05 May 2011 - 12:11 AM, said:

Also java is case sensitive, so B is not the same as b. I see them being uses interchangeably in your code a couple times.

They are probably the same in the opriginal code
It is this forum code formatter that capitalize b followed by a )
Was This Post Helpful? 0
  • +
  • -

#6 Tflaga   User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 44
  • Joined: 16-April 11

Re: Java Question on actionlistener(actionevent)

Posted 05 May 2011 - 07:19 AM

I don't see anything wrong with the b's i have in my code. Only time i really use b is in the actionevent(listener) class when i declare Button b = (Button)e.getSource(); With or without this line I'm still getting nullpointer exceptions(even then after I called the public void listener() class that was mentioned to do in the first reply. I think I'm close but since theres no compile errors I just can't pin point where the problem is.
Was This Post Helpful? 0
  • +
  • -

#7 v0rtex   User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Re: Java Question on actionlistener(actionevent)

Posted 05 May 2011 - 07:29 AM

You could also create a private class with the actionEvent for your button that when your button receives input, the class is called (with your embedded functionality coded into it) like so:
 private class checkWord implements ActionListener  {
    public void actionPerformed(ActionEvent e) {  
       processTurn();
        repaint();
    }
    }


Note: This code should work in hangman.java with some editing, no need for a new class just to recieve input.
public JButton Enter = new JButton("Enter text");
Enter.addActionListener(new checkWord());


Hope this helps,
v0rtex

This post has been edited by v0rtex: 05 May 2011 - 10:04 AM

Was This Post Helpful? 0
  • +
  • -

#8 exiles.prx   User is offline

  • D.I.C Head

Reputation: 65
  • View blog
  • Posts: 241
  • Joined: 22-November 10

Re: Java Question on actionlistener(actionevent)

Posted 05 May 2011 - 10:28 AM

View Postpbl, on 05 May 2011 - 04:42 AM, said:

View Postexiles.prx, on 05 May 2011 - 12:11 AM, said:

Also java is case sensitive, so B is not the same as b. I see them being uses interchangeably in your code a couple times.

They are probably the same in the opriginal code
It is this forum code formatter that capitalize b followed by a )


Ohhhh, I did not know that pbl so thank you. Therefore, I withdraw my statement about the b's. :bigsmile:

Tflaga, when is your null pointer exception occurring? Is it when you press the button? Try debugging and stepping through your code. When the null pointer exception appears, check your variables to see what is null and if you are attempting to perform a task on that variable that would cause the error.
Was This Post Helpful? 0
  • +
  • -

#9 v0rtex   User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Re: Java Question on actionlistener(actionevent)

Posted 05 May 2011 - 10:47 AM

rword = new String(temp[randomInt]);


You seem to be initializing your String with a non-string value (youre using an integer value), you should parse your data before initializing it so you are storing the correct datatype like so:
String data = Integer.parseInt(temp[randomInt]);


Or cast it to a String if possible, Also if you are getting a nullpointerexception then when you are declaring data or calling a method, you are either improperly declaring your data (check java documentation on the various datatypes if confused) or you are passing the wrong datatype when your method declares you need x datatype, so search your full code listing if that is occuring as well.
Was This Post Helpful? 0
  • +
  • -

#10 Tflaga   User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 44
  • Joined: 16-April 11

Re: Java Question on actionlistener(actionevent)

Posted 10 May 2011 - 02:04 PM

Hey I could really use some serious help with this code. I'm keeping the actionEvent in the same class but I NEED to change it from extending applet to JFrame. I created a main method and changed a couple of things and again like always I'm getting a null pointer exception error: Exception in thread "main" java.lang.NullPointerException
at hangmanrevised.createGame(hangmanrevised.java:66)
at hangmanrevised.<init>(hangmanrevised.java:35)
at hangmanrevised.main(hangmanrevised.java:202)

- one error is in the main method.
- one error when I call the create method() (so maybe something Im doing wrong in the createMethod()?
- and the other one is in the create method() to and the error points to: Letter.setText("");

Any help is greatly greatly appreciated. This code is due tonight and I'm running out of time and I'm completely ignorant when it comes to fixing these problems. I'm basically stuck. Thanks

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import java.lang.reflect.Array;
import javax.swing.*;


public class hangmanrevised extends JFrame implements ActionListener  {

	private int wrongs;
	private String right;
	private StringBuffer guess;
	private TextField Letter;
	private String message;
	private String information;
    private JButton button;
	private final int hung = 11;


	public hangmanrevised() {
	setSize(600,400);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());
    
    ImageIcon background = new ImageIcon("nightsky.png");
    TextField Letter = new TextField();
    JLabel label = new JLabel("pick a Letter");
    Button button = new Button("Enter");
    add(label);
    add(button);
    add(Letter);
    
    button.addActionListener(this);
    
    createGame(); //THIS IS WHERE ONE OF THE PROBLEMS IS WHEN i CALL THE METHOD.
    
	} 
	
         
	
	public void createGame(){
	     
	    wrongs = 0;
	     
	    String word = "school|java|programming|science|computer";
	    String[] temp;
	     
	    String delimiter = "\\|";
	     
	    temp = word.split(delimiter);
	     
	    Random randomPicker = new Random();
	     
	    
	    int randomWord = randomPicker.nextInt(temp.length);
	     
	    right = new String(temp[randomWord]);
	     
	    char positions[] = new char[right.length()];
	    for (int i = 0; i < right.length(); i++) {
	    positions[i] = '-';
		 
	    }
	    String s = new String(positions);
	    guess = new StringBuffer(s);
	     
	    Letter.setText(""); // THIS IS ANOTHER PROBLEM I THINK
	     
	    message="";
	    information = "";
	    repaint();
	    }
	     

	
	public void paint(Graphics g) {
	     super.paint(g);
		  //g.drawImage(background, 0, 156, Color.green, Enter);
		  
	         
	     int baseY = 350;
	     g.setColor(Color.lightGray);
		  g.drawRect(0, baseY,400,baseY);
	     g.fillRect(0, baseY,400,baseY);
			
			g.setColor(Color.darkGray);
			//g.drawRect(250,50,125,50);
		   //g.fillRect(250,50,125,50);
		     
		 if (wrongs > 0){ 
	    g.drawLine(125,baseY,125,baseY-100);
		 g.drawLine(123,baseY,123,baseY-100);
	    }
	    if (wrongs > 1){
	    g.drawLine(110,baseY,125,baseY-15);
	    g.drawLine(108,baseY,122,baseY-15);
		 }
	    if (wrongs > 2){
	    g.drawLine(140,baseY,125,baseY-15);
		 g.drawLine(138,baseY,122,baseY-15);
	    }
	    if (wrongs > 3){ 
	    g.drawLine(125,baseY-100,175,baseY-100);
		 g.drawLine(125,baseY-98,175,baseY-98);
	    }
	    if (wrongs > 4){ 
	    g.drawLine(175,baseY-100,175,baseY-75);
	    }
	    if (wrongs > 5){ 
	    g.drawOval(170,baseY-75,10,12);
	    }
	    if (wrongs > 6){
	    g.drawOval(160,baseY-65,15,25);
		 g.fillOval(160,baseY-65,15,25);
	    }
	    if (wrongs > 7){ 
	    g.drawLine(150,baseY-65,170,baseY-60);
	    }
	    if (wrongs > 8){
	    g.drawLine(173,baseY-60,193,baseY-65);
	    }
	    if (wrongs > 9){ 
	    g.drawLine(155,baseY-30,170,baseY-45);
	    }
	    if (wrongs > 10){
	    g.drawLine(173,baseY-45,193,baseY-30);
	    }
	     
	    
	    g.drawString( message, 60, baseY+25 );
	    g.drawString( information, 25, baseY+45 );
	    g.drawString( new String (guess), 110, 60);
	     //listener();
	    }

public void actionPerformed(ActionEvent e){
	    
	    if (e.getSource() == button){
	     
	    processTurn();
	     
	    Letter.setText("");
	    repaint();
	    }
	    }
	
	private void processTurn(){
	    String s, t;
	    char a;
	    
	    s = Letter.getText();
	    a = s.charAt(0);
	     
	    if (!Character.isLetter(a)){
	    message="Letters only";
	    return;
	    }
	    if (s.length()>1){
	    message="Enter 1 letter only";
	    return;
	    }
	          
	    t = new String(guess);
	    if (t.indexOf(s) != -1){
	    JOptionPane.showMessageDialog(null, "LETTER USED ALREADY");
		 
	    return;
	    }
	     
	    
	     
	    if (right.indexOf(s) == -1){
	    message="";
	    wrongs++;
	    if (wrongs == hung){
	    JOptionPane.showMessageDialog(null, "YOU LOST!");
		 
	    
	    }
	     
	    return;
	    }
	     
	    for (int i = 0; i < right.length(); i++){
	    if (right.charAt(i) == a){
	    guess.setCharAt(i, a);
	    }
	    }
	    t = new String(guess);
	     
	         
	    if (t.indexOf('-') == -1){
	  JOptionPane.showMessageDialog(null, "YOU WIN!");
	  message="You win!";
	    return;
	    }
	     
	    message="";
	    repaint();
	    }

	public static void main(String[] args) {
	hangmanrevised f = new hangmanrevised(); // AND THIS IS WHERE ANOTHER NULL POINTER EXCEPTION OCCURS ACCORDING //TO THE COMPILE ERROR.
        f.setVisible(true);
         
	}
}




Was This Post Helpful? 0
  • +
  • -

#11 exiles.prx   User is offline

  • D.I.C Head

Reputation: 65
  • View blog
  • Posts: 241
  • Joined: 22-November 10

Re: Java Question on actionlistener(actionevent)

Posted 10 May 2011 - 05:49 PM

Unless the forum auto format is pulling another fast one on me, it could be caused by the fact that your using Letter and button twice for two different objects. One getting initialized the other one not. Could be confusing the compiler as to what variable/object your trying to perform a task on.

            private int wrongs;
	    private String right;
	    private StringBuffer guess;
	    private TextField Letter;    //Letter here.... 1
	    private String message;
	    private String information;
	    private JButton button;      //button here... 1
	    private final int hung = 11;
	 
	 
	    public hangmanrevised() {
	    setSize(600,400);
	    setLocationRelativeTo(null);
	    setDefaultCloseOperation(EXIT_ON_CLOSE);
	    setLayout(new FlowLayout());
	     
	    ImageIcon background = new ImageIcon("nightsky.png");
	    TextField Letter = new TextField();             //Letter here.... 2
	    JLabel label = new JLabel("pick a Letter");
            Button button = new Button("Enter");            //button here.... 2


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1