473,320 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

using java textfields

In my project "scientific calculator", im using 2 textfields in my GUI app. the problem now (or actually what i dislike) is the user has to use the 2 textfields even if he needs a function of only 1 parameter as trig functions and roots.
when i enter 1 value in the first textfield and leave the other blank, the program doesnt give any output.
Is there any way so i can use only 1 textfield for functions which take 1 parameter?
Dec 18 '07 #1
3 2958
SammyB
807 Expert 512MB
You'll need to give us more details. For single operand functions like sin and 1/x, a "normal" calculator would get the single operand from the display and replace the display with the results. For double operand functions like x mod y and x**y, you get the x from the display when the user presses the function button and you get the y from the display when the user presses = and display the results. So, having textfields doesn't make sense.
Dec 18 '07 #2
For double operand functions like x mod y and x**y, you get the x from the display when the user presses the function button and you get the y from the display when the user presses = and display the results. So, having textfields doesn't make sense.
first: did u mean i should use a stack so i get the operand (y) which comes immediately before the equal sign and the operand (x) that comes immediately before the operator ??

second: how can i use a textfield more than once instead of having multiple textfields??
Dec 19 '07 #3
SammyB
807 Expert 512MB
> should use a stack ?
You only need to have a class-level variable for the first operand and get the second operand from the textfield. That's sort of a stack, but a very small one.

> how can i use a textfield more than once
Take a look at the code I wrote for a simple calculator and try to understand it first, then think about how to add some scientific buttons. Notice that when an operator key is first pressed, I get the number from the textfield and store it in dDisplay, then on subsequent operator presses, I combine dDisplay with the current contents of the textfield.

Note, this is just a very simple calculator. If you want to have parentheses keys, then you will have to use a stack and the code will be more confusing.
Expand|Select|Wrap|Line Numbers
  1. /*
  2.  * Chapter 6:    Calculator
  3.  * Programmer:   Sam Barrett
  4.  * Date:         24 Oct 2007
  5.  * Filename:     Calculator.java
  6.  * Purpose:      This program creates a calculator with a menu. 
  7.  * Change Notes: Created an array of 'key caps' to make button creation easier.
  8.  *             Did all of the button stuff in a single loop.
  9.  *             Used the first letter of the menu & keys in a single switch statement.
  10.  *             Corrected the code so that it works like a regular calculator. 
  11.  *             (Their code for = was wrong)
  12.  *             Made the button font readable and the buttons square.
  13.  *             Changed some variable names to ones that I liked better.
  14.  *             Demoted the class-level variables that did not need to be class-level.
  15.  *             Made it more modular.     
  16.  */
  17. import java.awt.*;
  18. import java.awt.datatransfer.*;
  19. import java.awt.event.ActionEvent;
  20. import java.awt.event.ActionListener;
  21. import java.awt.event.WindowAdapter;
  22. import java.awt.event.WindowEvent;
  23. import java.text.DecimalFormat;
  24. import javax.swing.JOptionPane;
  25.  
  26. public class Calculator extends Frame implements ActionListener 
  27. {
  28.    private TextField answerField;
  29.    private boolean isFirstOperand = true;
  30.    private boolean isClearPending = true;
  31.    private char cLastOp;
  32.    private double dDisplay = 0.0;
  33.    private DecimalFormat fmtDisplay = new DecimalFormat("########.########");
  34.    private String[] sKeyCaps = {"7","8","9","/",
  35.                            "4","5","6","*",
  36.                            "1","2","3","-",
  37.                            "0",".","=","+"};
  38.    public Calculator()
  39.    {
  40.       //Create Menu
  41.       MenuBar mnuBar = new MenuBar();
  42.       this.setMenuBar(mnuBar);
  43.       Menu mnuFile = new Menu("File", true);
  44.       mnuBar.add(mnuFile);
  45.       MenuItem mnuFileExit = new MenuItem("Exit");
  46.       mnuFileExit.addActionListener(this);
  47.       mnuFile.add(mnuFileExit);
  48.       Menu mnuEdit = new Menu("Edit", true);
  49.       mnuBar.add(mnuEdit);
  50.       MenuItem mnuEditClear = new MenuItem("Clear");
  51.       mnuEditClear.addActionListener(this);
  52.       mnuEdit.add(mnuEditClear);
  53.       MenuItem mnuEditCopy = new MenuItem("Copy");
  54.       mnuEditCopy.addActionListener(this);
  55.       mnuEdit.add(mnuEditCopy);
  56.       MenuItem mnuEditPaste = new MenuItem("Paste");
  57.       mnuEditPaste.addActionListener(this);
  58.       mnuEdit.add(mnuEditPaste);
  59.       Menu mnuAbout = new Menu("About", true);
  60.       mnuBar.add(mnuAbout);
  61.       MenuItem mnuAboutCalc = new MenuItem("About Caculator");
  62.       mnuAboutCalc.addActionListener(this);
  63.       mnuAbout.add(mnuAboutCalc);
  64.  
  65.       //Create Components
  66.       answerField = new TextField(20);
  67.       answerField.setEditable(false);
  68.  
  69.       //Setup Frame & Layouts & buttons
  70.       this.setLayout(new BorderLayout());
  71.       Panel keysPanel = new Panel();
  72.       keysPanel.setLayout(new GridLayout(4,4,10,10));
  73.       Font f = new Font("Verdana", Font.BOLD, 20);
  74.       Button[] keys = new Button[16];
  75.       for (int i=0; i<16; i++)
  76.       {
  77.          keys[i] = new Button(sKeyCaps[i]);
  78.          keys[i].setFont(f);
  79.          keys[i].addActionListener(this);
  80.          keysPanel.add(keys[i]);
  81.       }
  82.       this.add(answerField, BorderLayout.NORTH);
  83.       this.add(keysPanel, BorderLayout.CENTER);
  84.  
  85.       clearCalculator();
  86.  
  87.       this.addWindowListener(
  88.          new WindowAdapter()
  89.          {
  90.             public void windowClosing(WindowEvent e)
  91.             { System.exit(0); }
  92.          }
  93.       );
  94.    }
  95.    public void actionPerformed(ActionEvent e) 
  96.    {
  97.       String sItem = e.getActionCommand();
  98.       char cFirst = sItem.charAt(0);
  99.       switch (cFirst)
  100.       {
  101.       case 'E':               // Exit
  102.          System.exit(0);
  103.          break;
  104.       case 'C':               // Clear or Copy
  105.          if (sItem == "Clear")
  106.             clearCalculator();
  107.          else if (sItem == "Copy")
  108.          {
  109.             Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
  110.             StringSelection contents = new StringSelection(answerField.getText());
  111.             cb.setContents(contents, null);
  112.          }
  113.          break;
  114.       case 'P':               // Paste
  115.          Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
  116.          Transferable contents = cb.getContents(this);
  117.          try
  118.          {
  119.             String s = (String)contents.getTransferData((DataFlavor.stringFlavor));
  120.             answerField.setText(fmtDisplay.format(Double.parseDouble(s)));
  121.          }
  122.          catch (Throwable ex)
  123.          {
  124.             clearCalculator();
  125.          }
  126.          break;
  127.       case 'A':               // About
  128.          JOptionPane.showMessageDialog(this, 
  129.                "Calculator ver. 1.0\nCornerStone Software\nCopyright 2007\nAll rights reserved", 
  130.                "About Calculator", JOptionPane.INFORMATION_MESSAGE);
  131.          break;
  132.       case '0': case '1': case '2': case '3': case '4': case '5':      // Numbers
  133.       case '6': case '7': case '8': case '9': case '.':
  134.          if (isClearPending)      // Start of a new operand
  135.          {
  136.             answerField.setText("");
  137.             isClearPending = false;
  138.          }
  139.          answerField.setText(answerField.getText() + sItem);
  140.          break;
  141.       case '+': case '-': case '*': case '/': case '=':            // Operators
  142.          if (isFirstOperand)
  143.             processFirstOp(cFirst);
  144.          else
  145.             processNextOp(cFirst);
  146.          break;
  147.       }
  148.    }
  149.  
  150.    public void clearCalculator()
  151.    {
  152.       isFirstOperand = true;
  153.       answerField.setText("");
  154.       answerField.requestFocus();
  155.    }
  156.    public void processFirstOp(char cOp)
  157.    {
  158.       String s = answerField.getText();
  159.       if (s=="")
  160.          dDisplay = 0.0;
  161.       else
  162.          dDisplay = Double.parseDouble(s);
  163.       isClearPending = true;
  164.       isFirstOperand = false;
  165.       cLastOp = cOp;
  166.    }
  167.  
  168.    public void processNextOp(char cOp)
  169.    {
  170.       String s = answerField.getText();
  171.       if (s!="")
  172.       {
  173.          Double d = Double.parseDouble(s);
  174.          switch (cLastOp)   // Note, = falls thru: nothing to do but set ClearPending
  175.          {
  176.          case '+':
  177.             dDisplay += d;
  178.             break;
  179.          case '-':
  180.             dDisplay -= d;
  181.             break;
  182.          case '*':
  183.             dDisplay *= d;
  184.             break;
  185.          case '/':
  186.             dDisplay /= d;
  187.             break;
  188.          }
  189.          answerField.setText(fmtDisplay.format(dDisplay));
  190.          isClearPending = true;
  191.       }
  192.       cLastOp = cOp;
  193.    }
  194.  
  195.    public static void main(String[] args) 
  196.    {
  197.       //Setup the frame
  198.       Calculator frm = new Calculator();
  199.       frm.setTitle("Calculator Application");
  200.       frm.setBounds(200, 200, 250, 300);
  201.       frm.setVisible(true);
  202.  
  203.       //Setup an icon
  204.       Image icon = Toolkit.getDefaultToolkit().getImage("calcImage.gif");
  205.       frm.setIconImage(icon);
  206.    }
  207. }
  208.  
Dec 19 '07 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: R.G. Vervoort | last post by:
I would like to select an option in a pulldown, select a record in a mysql database depending on the pulldown selection and then put the data from the record in the textfields. I can retrieve...
1
by: Ed | last post by:
Hi, I have an html page with a div element within a form for dynamically creating textfields. The problem is when I click a link on the page, or the submit button, then click the back button,...
6
by: anirban.anirbanju | last post by:
hi there, i've some serious problem to add rows dynamically in a table. my table contains 5 cell. | check | from_value | to_value | color_text | color_value |...
6
by: rohayre | last post by:
Im a long time java developer and actually have never done anything with java scripting. I'd like to write a short simple script for calculating a date in the future based on today's date and a...
6
by: haran22 | last post by:
verify and tell me what runtime error in this pgm import java.awt.*; import java.applet.*; import java.awt.event.*; import java.sql.*; public class screen extends Applet implements...
3
by: nicky77 | last post by:
Hi there, newish to javascript so grateful for any help. I am creating a test generator and have an array of textfields ("answer") created by a simple piece of PHP code. As you can see, I have...
2
by: star111792 | last post by:
Hello all, i m doing networking in java. i m trying to build a client/server appplication in which i m trying to create a simple login page. tasks that im trying to do are in following sequence: ...
5
by: Kevin R | last post by:
How do you create those small textfields that I see for inputing passwords and such? Kevin
2
by: f3dde | last post by:
Hi there, I have a question about forms in MS Access.. Is it possible in any way at all, to add info in 2 textfields and save it as 1 record. Detail: I have a record with 3 fields....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.