Hi :)
I was messing around with java applets just now, and I can't seem to figure out how to put more than one event handler in an applet. I'm just working on a really simple calculator. Three buttons, one to add, one to subtract and one to clear everything. I know it can easily be done with one event handler, but it's not about the program, just about learning how to use more than one. Here's the code, any idea what's wrong? Thanks!

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

public class calculator extends JApplet
	static JLabel resultLabel;
	static JLabel entryLabel;
	static JLabel outputLabel;
	static JTextField enterNum;
	static JButton adding;
	static JButton subtracting;
	static JButton clearbutton;
	static double result;

          //listener for clear button
	static class clearHandler implements ActionListener
		public void actionPerformed(ActionEvent event)

           //listener for adding and subtracting buttons
	static class operatorHandler implements ActionListener
		public void actionPerformed(ActionEvent event)
			double secondoperand=0.0;
			String whichbutton=event.getActionCommand();
			if (whichbutton.equals("+"))
			else if (whichbutton.equals("-"))
			result =result-secondoperand;
			outputLabel.setText(result+" ");


	operatorHandler operation;
	clearHandler clearing;

	public void init()
	resultLabel=new JLabel("result: ");
	entryLabel=new JLabel("enter #: ");
	outputLabel=new JLabel("0.0");
	adding=new JButton("+");
	subtracting=new JButton("-");
	clearbutton =new JButton("clear");
	enterNum=new JTextField("value here ",10);


	setLayout(new GridLayout(4,1));


Recommended Answers

All 8 Replies

1. what errors do you actually get?
2. ALL class names should begin with a capital
3. you never actually initialize your handlers operatorHandler operation [b]= new operatorHandler();[/b]

commented: This is the real answer - mine was just a nitpick :) +11

Also, don't make everything in your class static for no reason.

commented: can't believe i didn't notice nice catch +1

oh, i didn't notice nice catch

Well, you caught #3, which is the root of the poster's problem. The static thing was just an aside :)

Thank you! the error was that the buttons weren't doing anything, which is now fixed. But I didn't get why I should capitalize my class names? is that just common practice or is there a reason for it?

Cool, never knew that existed. thanks!

Sorry if this is the wrong forum now. But how can I view my applet in a web browser? I used the code below, and I also uploaded operatorHandler.class and clearHandler.class to the directory. Should I have made a .jar file? If so, how?

<applet code="calculator.class" codebase="I put it- don't know it off hand"  width=200 height=200></applet>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.