using java textfields

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bravephantom
    New Member
    • Dec 2006
    • 27

    #1

    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?
  • SammyB
    Recognized Expert Contributor
    • Mar 2007
    • 807

    #2
    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.

    Comment

    • bravephantom
      New Member
      • Dec 2006
      • 27

      #3
      Originally posted by SammyB
      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??

      Comment

      • SammyB
        Recognized Expert Contributor
        • Mar 2007
        • 807

        #4
        > 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.
        [code=java]
        /*
        * Chapter 6: Calculator
        * Programmer: Sam Barrett
        * Date: 24 Oct 2007
        * Filename: Calculator.java
        * Purpose: This program creates a calculator with a menu.
        * Change Notes: Created an array of 'key caps' to make button creation easier.
        * Did all of the button stuff in a single loop.
        * Used the first letter of the menu & keys in a single switch statement.
        * Corrected the code so that it works like a regular calculator.
        * (Their code for = was wrong)
        * Made the button font readable and the buttons square.
        * Changed some variable names to ones that I liked better.
        * Demoted the class-level variables that did not need to be class-level.
        * Made it more modular.
        */
        import java.awt.*;
        import java.awt.datatr ansfer.*;
        import java.awt.event. ActionEvent;
        import java.awt.event. ActionListener;
        import java.awt.event. WindowAdapter;
        import java.awt.event. WindowEvent;
        import java.text.Decim alFormat;
        import javax.swing.JOp tionPane;

        public class Calculator extends Frame implements ActionListener
        {
        private TextField answerField;
        private boolean isFirstOperand = true;
        private boolean isClearPending = true;
        private char cLastOp;
        private double dDisplay = 0.0;
        private DecimalFormat fmtDisplay = new DecimalFormat(" ########.###### ##");
        private String[] sKeyCaps = {"7","8","9" ,"/",
        "4","5","6","*" ,
        "1","2","3" ,"-",
        "0",".","=","+" };
        public Calculator()
        {
        //Create Menu
        MenuBar mnuBar = new MenuBar();
        this.setMenuBar (mnuBar);
        Menu mnuFile = new Menu("File", true);
        mnuBar.add(mnuF ile);
        MenuItem mnuFileExit = new MenuItem("Exit" );
        mnuFileExit.add ActionListener( this);
        mnuFile.add(mnu FileExit);
        Menu mnuEdit = new Menu("Edit", true);
        mnuBar.add(mnuE dit);
        MenuItem mnuEditClear = new MenuItem("Clear ");
        mnuEditClear.ad dActionListener (this);
        mnuEdit.add(mnu EditClear);
        MenuItem mnuEditCopy = new MenuItem("Copy" );
        mnuEditCopy.add ActionListener( this);
        mnuEdit.add(mnu EditCopy);
        MenuItem mnuEditPaste = new MenuItem("Paste ");
        mnuEditPaste.ad dActionListener (this);
        mnuEdit.add(mnu EditPaste);
        Menu mnuAbout = new Menu("About", true);
        mnuBar.add(mnuA bout);
        MenuItem mnuAboutCalc = new MenuItem("About Caculator");
        mnuAboutCalc.ad dActionListener (this);
        mnuAbout.add(mn uAboutCalc);

        //Create Components
        answerField = new TextField(20);
        answerField.set Editable(false) ;

        //Setup Frame & Layouts & buttons
        this.setLayout( new BorderLayout()) ;
        Panel keysPanel = new Panel();
        keysPanel.setLa yout(new GridLayout(4,4, 10,10));
        Font f = new Font("Verdana", Font.BOLD, 20);
        Button[] keys = new Button[16];
        for (int i=0; i<16; i++)
        {
        keys[i] = new Button(sKeyCaps[i]);
        keys[i].setFont(f);
        keys[i].addActionListe ner(this);
        keysPanel.add(k eys[i]);
        }
        this.add(answer Field, BorderLayout.NO RTH);
        this.add(keysPa nel, BorderLayout.CE NTER);

        clearCalculator ();

        this.addWindowL istener(
        new WindowAdapter()
        {
        public void windowClosing(W indowEvent e)
        { System.exit(0); }
        }
        );
        }
        public void actionPerformed (ActionEvent e)
        {
        String sItem = e.getActionComm and();
        char cFirst = sItem.charAt(0) ;
        switch (cFirst)
        {
        case 'E': // Exit
        System.exit(0);
        break;
        case 'C': // Clear or Copy
        if (sItem == "Clear")
        clearCalculator ();
        else if (sItem == "Copy")
        {
        Clipboard cb = Toolkit.getDefa ultToolkit().ge tSystemClipboar d();
        StringSelection contents = new StringSelection (answerField.ge tText());
        cb.setContents( contents, null);
        }
        break;
        case 'P': // Paste
        Clipboard cb = Toolkit.getDefa ultToolkit().ge tSystemClipboar d();
        Transferable contents = cb.getContents( this);
        try
        {
        String s = (String)content s.getTransferDa ta((DataFlavor. stringFlavor));
        answerField.set Text(fmtDisplay .format(Double. parseDouble(s)) );
        }
        catch (Throwable ex)
        {
        clearCalculator ();
        }
        break;
        case 'A': // About
        JOptionPane.sho wMessageDialog( this,
        "Calculator ver. 1.0\nCornerSton e Software\nCopyr ight 2007\nAll rights reserved",
        "About Calculator", JOptionPane.INF ORMATION_MESSAG E);
        break;
        case '0': case '1': case '2': case '3': case '4': case '5': // Numbers
        case '6': case '7': case '8': case '9': case '.':
        if (isClearPending ) // Start of a new operand
        {
        answerField.set Text("");
        isClearPending = false;
        }
        answerField.set Text(answerFiel d.getText() + sItem);
        break;
        case '+': case '-': case '*': case '/': case '=': // Operators
        if (isFirstOperand )
        processFirstOp( cFirst);
        else
        processNextOp(c First);
        break;
        }
        }

        public void clearCalculator ()
        {
        isFirstOperand = true;
        answerField.set Text("");
        answerField.req uestFocus();
        }
        public void processFirstOp( char cOp)
        {
        String s = answerField.get Text();
        if (s=="")
        dDisplay = 0.0;
        else
        dDisplay = Double.parseDou ble(s);
        isClearPending = true;
        isFirstOperand = false;
        cLastOp = cOp;
        }

        public void processNextOp(c har cOp)
        {
        String s = answerField.get Text();
        if (s!="")
        {
        Double d = Double.parseDou ble(s);
        switch (cLastOp) // Note, = falls thru: nothing to do but set ClearPending
        {
        case '+':
        dDisplay += d;
        break;
        case '-':
        dDisplay -= d;
        break;
        case '*':
        dDisplay *= d;
        break;
        case '/':
        dDisplay /= d;
        break;
        }
        answerField.set Text(fmtDisplay .format(dDispla y));
        isClearPending = true;
        }
        cLastOp = cOp;
        }

        public static void main(String[] args)
        {
        //Setup the frame
        Calculator frm = new Calculator();
        frm.setTitle("C alculator Application");
        frm.setBounds(2 00, 200, 250, 300);
        frm.setVisible( true);

        //Setup an icon
        Image icon = Toolkit.getDefa ultToolkit().ge tImage("calcIma ge.gif");
        frm.setIconImag e(icon);
        }
        }
        [/code]

        Comment

        Working...