Meaningless Drivel is fun!
The moose likes Java in General and the fly likes please help with calculator prgram Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "please help with calculator prgram" Watch "please help with calculator prgram" New topic

please help with calculator prgram

dave ash

Joined: Mar 20, 2006
Posts: 5

i am currently writing a calculator which looks and acts like the windows calculator, i have got the layout and buttons to appear but that's it. i am having trouble with the rest, how would i make the buttons work, like when 1 is clicked a 1 apears in the textfield etc. can anybody offer any asistance??

thanks in advance.

here is the code i have so far

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

// Name: Dave Ash

public class Calculator extends JFrame implements ActionListener
JButton[] btnNums;
JButton btnBack;
JButton btnClear;
JButton btnCalculate;

JTextField txtDisplay;

public Calculator()
Container content = getContentPane();

JPanel jpDisplay = new JPanel();
jpDisplay.setLayout(new BorderLayout());
txtDisplay = new JTextField(15);

JPanel jpRow2 = new JPanel();
btnBack = new JButton("Backspace");
btnClear = new JButton("Clear");

String[] strNames = {"MC","7","8", "9","/","sqrt","MR","4", "5", "6","*","%","MS","1", "2", "3","+","1x","M+","0", "+/-", ".", "-","=",};
btnNums = new JButton[24];
JPanel jpButtons = new JPanel();
jpButtons.setLayout(new GridLayout(4,6));

for (int i = 0; i < 24; i++)
btnNums[i] = new JButton(strNames[i]);

setLayout(new FlowLayout());
content.add(jpDisplay, BorderLayout.NORTH);
setTitle("Mini Calculator");


public void actionPerformed(ActionEvent ae)

public static void main(String[] args)
Calculator calc = new Calculator();
satishkumar janakiraman
Ranch Hand

Joined: May 03, 2004
Posts: 334

The following line throws an error
.Please comment it.

I have given the sample statement to print the value in the textfield. but its not an ideal approach.

try and post your comment if it works.
bye for now
dave ash

Joined: Mar 20, 2006
Posts: 5
i was thinking of useing something like an actionlistner for the button's but dont have a clue of how to do that.

thanks for the advice but when i comment out the code my backspace and clear disapear,
i am useing textpad to program my code.
Joe Ess

Joined: Oct 29, 2001
Posts: 9150

Sat must be using a 1.4 or earlier JDK. Your code does not throw an exception in JDK 1.5.
Have a look at the Java Tutorial on Swing for how to hook up an ActionListener.

[How To Ask Questions On JavaRanch]
I agree. Here's the link:
subject: please help with calculator prgram
jQuery in Action, 3rd edition