Calculator in Swing

Hi all,
wanted a smal mangable code for simulating a calculator in swing.
Please provide me a link to the whereabouts of finding such a code.
Thanks in advance
Preets

import java.awt.*;
import java.lang.*;
import javax.swing.*;
public class Calculator extends JFrame {
JTextField text;
String sText1, sText2;
double dReg1, dReg2, dMem;
String sOperator;
boolean isFixReg;
public Calculator() {
initProperty();
Panel pFrame = new Panel();
pFrame.setLayout(new FlowLayout());
text = new JTextField("");
text.setHorizontalAlignment(JTextField.RIGHT);
text.setEditable(false);
text.setBackground(Color.white);
Panel pCalc = new Panel();
pCalc.setLayout(new BorderLayout(0, 10));
pCalc.add("North", text);
pFrame.add("Center", pCalc);
Panel pKey = new Panel();
pKey.setLayout(new GridLayout(5, 4, 5, 5));
getContentPane().add("Center", pKey);
pKey.add(new Button("C"));
pKey.add(new Button("MR"));
pKey.add(new Button("M-"));
pKey.add(new Button("M+"));
pKey.add(new Button("7"));
pKey.add(new Button("8"));
pKey.add(new Button("9"));
pKey.add(new Button("/"));
pKey.add(new Button("4"));
pKey.add(new Button("5"));
pKey.add(new Button("6"));
pKey.add(new Button("*"));
pKey.add(new Button("1"));
pKey.add(new Button("2"));
pKey.add(new Button("3"));
pKey.add(new Button("-"));
pKey.add(new Button("0"));
pKey.add(new Button("."));
pKey.add(new Button("="));
pKey.add(new Button("+"));
pCalc.add("South", pKey);
getContentPane().setLayout(new BorderLayout(0, 0));
getContentPane().add("Center", pFrame);
dReg1 = 0.0d;
dReg2 = 0.0d;
dMem = 0.0d;
sOperator = "";
text.setText("0");
isFixReg = true;
* property
private void initProperty() {
setSize(175, 215);
setLocation(50, 100);
setTitle("Calculator");
setVisible(true);
     public boolean action(Event evt, Object arg) {
          if ("C".equals(arg))
dReg1 = 0.0d;
dReg2 = 0.0d;
sOperator = "";
text.setText("0");
isFixReg = true;
else if (("0".equals(arg)) | ("1".equals(arg)) | ("2".equals(arg))
| ("3".equals(arg)) | ("4".equals(arg)) | ("5".equals(arg))
| ("6".equals(arg)) | ("7".equals(arg)) | ("8".equals(arg))
| ("9".equals(arg)) | (".".equals(arg)))
if (isFixReg)
sText2 = (String) arg;
else
sText2 = text.getText() + arg;
text.setText(sText2);
isFixReg = false;
else if (("+".equals(arg)) | ("-".equals(arg))
| ("*".equals(arg)) | ("/".equals(arg)) | ("=".equals(arg)))
sText1 = text.getText();
dReg2 = (Double.valueOf(sText1)).doubleValue();
dReg1 = Calculation(sOperator, dReg1, dReg2);
Double dTemp = new Double(dReg1);
sText2 = dTemp.toString();
text.setText(sText2);
sOperator = (String) arg;
isFixReg = true;
          else if ("MR".equals(arg))
Double dTemp = new Double(dMem);
sText2 = dTemp.toString();
text.setText(sText2);
sOperator = "";
isFixReg = true;
          else if ("M+".equals(arg))
sText1 = text.getText();
dReg2 = (Double.valueOf(sText1)).doubleValue();
dReg1 = Calculation(sOperator, dReg1, dReg2);
Double dTemp = new Double(dReg1);
sText2 = dTemp.toString();
text.setText(sText2);
dMem = dMem + dReg1;
sOperator = "";
isFixReg = true;
          else if ("M-".equals(arg))
sText1 = text.getText();
dReg2 = (Double.valueOf(sText1)).doubleValue();
dReg1 = Calculation(sOperator, dReg1, dReg2);
Double dTemp = new Double(dReg1);
sText2 = dTemp.toString();
text.setText(sText2);
dMem = dMem - dReg1;
sOperator = "";
isFixReg = true;
return true;
private double Calculation(String sOperator, double dReg1, double dReg2)
if ("+".equals(sOperator)) dReg1 = dReg1 + dReg2;
else if ("-".equals(sOperator)) dReg1 = dReg1 - dReg2;
else if ("*".equals(sOperator)) dReg1 = dReg1 * dReg2;
else if ("/".equals(sOperator)) dReg1 = dReg1 / dReg2;
else dReg1 = dReg2;
return dReg1;

Similar Messages

  • Calculator using swing

    hello everyone,
    I am new toprogramming and alst to java language. can anybody help me in writing calculator using java swing.
    the functionality of the calculator should be same as the one we use in windows operating system
    please help me

    please help meSure, what problem to you have?
    if you are starting from scratch, get a copy of this book
    http://www.amazon.com/gp/product/1931841608/qid=1144486744/sr=2-1/ref=pd_bbs_b_2_1/002-4043290-4676869?s=books&v=glance&n=283155
    which builds a calculator throughout the book

  • Java Swing Project

    Im totally new to Swing, and fairly new to the java programming language as well. Could anyone point me in the right direction to a good beginner tutorial. I have tried the ones on the sun website and googled a few others but none really help me with what i am trying to do, which is try to build a calculator using swing. I am trying to display it in the top left hand corner. Managed to get it working , but the layout things really confuse me, so i got what i wanted by allowing the window not to be resized....but now im not sure if i can add to it to get it to where i want now :(. Any help gratefully received!

    Oh, I thought you meant the top-left corner of the monitor. With questions like this there is only one way to get the best possible answers. But that one way asks you to do a little bit of work. Create the simplest possible example program that demonstrates your problem and post that. Then forum members can run it and see what you mean.

  • How to convert class file into exe

    I have made a simple calculator using swing.now i want it to be used as an application from the desktop..How can i do it?..any suggestions?

    raghu0007 wrote:
    I have converted the class file to jar using jar cvf simplecalci.jar simplecalci.class.
    Now i don't know wat to do next since when i double click the jar.....windows shows the message
    Failed to load Main-class manifest attribute from c:\users\raghu\simplecalculator\build\classes\simplecalculator\simplecalci.jar
    I am using netbeans and i have JRE 5 as well as JRE 6 installed.
    I don't knw wat to do.Netbeans creates the .jar file for you,
    Simply right click on the project node in nb and select
    clean and buildnext goto the location of the project
    Eg:
    C:\Documents and Settings\raghu0007\My Documents\NetBeans Projects\SimpleCalculcator\dist\There will usually be 2 files in there, 1 for the Gui parts and the other(.jar) the rest.
    These two files must always be together (same directory for the jar file to work)
    copy the dist folder to C:\Program Files\, Rename it and create a shortcut to the simplecalci.jar file
    If you know the above just take a look at how you modified the MANAFEST file and the file(MF,class...) locations in the .jar
    For Windows XP
    Edited by: gtRpr on 2008/06/20 09:48

  • ActionEvents

    I am a student working on a simple project, or so I thought. I have to design a calculator using Swing. I have the application set up, but I need help understanding actionEvents. My GUI looks good, all buttons have actionEvents attached to them, my LCD display works fine, but I have one major problem.
    I am trying to set up my actionEvents like this.
    I have one set declared within my Calculator class that simply adds a number to a string, so if the user pushes "1", then "2", then "7", my string will be 127.
    I have another class that implements actionListener and is used for the plus, minus, divide, etc. buttons. This class saves the current string in the LCD display and then clears the LCD display.
    I plan on using this structure, but don't know if it is a good setup or not. I would also like to know how I can pass strings between these classes. For example, when a user pushes the "+" button, the actionListener function that is called is outside of my Calculator Class. Therefore, I have to pass the LCDdisplay to this function. I would then like to save the LCDdisplay string, clear it, and pass back the what I saved. Can I do this.
    Any help would be greatly appreciated.
    Thanks,
    Cleatis

    I am a student working on a simple project, or so I thought. I have to design a calculator using Swing. I have the application set up, but I need help understanding actionEvents. My GUI looks good, all buttons have actionEvents attached to them, my LCD display works fine, but I have one major problem.
    I am trying to set up my actionEvents like this.
    I have one set declared within my Calculator class that simply adds a number to a string, so if the user pushes "1", then "2", then "7", my string will be 127.
    I have another class that implements actionListener and is used for the plus, minus, divide, etc. buttons. This class saves the current string in the LCD display and then clears the LCD display.
    I plan on using this structure, but don't know if it is a good setup or not. I would also like to know how I can pass strings between these classes. For example, when a user pushes the "+" button, the actionListener function that is called is outside of my Calculator Class. Therefore, I have to pass the LCDdisplay to this function. I would then like to save the LCDdisplay string, clear it, and pass back the what I saved. Can I do this.
    Any help would be greatly appreciated.
    Thanks,
    Cleatis

  • Please add keyboard focus events to swing calculator.  Its very argent.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    A frame with a calculator panel.
    class CalculatorFrame1 extends JFrame
         private static final long serialVersionUID=0;
    public CalculatorFrame1()
    setTitle("Calculator");
    Container contentPane = getContentPane();
    CalculatorPanel panel = new CalculatorPanel();
    contentPane.add(panel);
    pack();
    setVisible(true);
    public static void main(String[] args)
    CalculatorFrame1 frame = new CalculatorFrame1();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.show();
    A panel with calculator buttons and a result display.
    class CalculatorPanel extends JPanel implements KeyListener
    private static final long serialVersionUID=0;
    private JTextField display;
    private JPanel panel;
    private double result;
    private String lastCommand;
    private boolean start;
    public CalculatorPanel()
    setLayout(new BorderLayout());
    result = 0;
    lastCommand = "=";
    start = true;
    // add the display
    display = new JTextField("");
    // display.addKeyListener(this);
    // display.addKeyListener(this);
    add(display, BorderLayout.NORTH);
    display.setFocusable(true);
    ActionListener insert = new InsertAction();
    ActionListener command = new CommandAction();
    // add the buttons in a 4 x 4 grid
    panel = new JPanel();
    panel.setLayout(new GridLayout(5, 4));
    addButton("7", insert);
    addButton("8", insert);
    addButton("9", insert);
    addButton("/", command);
    addButton("4", insert);
    addButton("5", insert);
    addButton("6", insert);
    addButton("*", command);
    addButton("1", insert);
    addButton("2", insert);
    addButton("3", insert);
    addButton("-", command);
    addButton("0", insert);
    addButton(".", insert);
    addButton("=", command);
    addButton("+", command);
    addButton("Clear", command);
    add(panel, BorderLayout.CENTER);
    //this.addKeyListener(this);
    Adds a button to the center panel.
    @param label the button label
    @param listener the button listener
    private void addButton(String label, ActionListener listener)
    JButton button = new JButton(label);
    button.addActionListener(listener);
    panel.add(button);
    This action inserts the button action string to the
    end of the display text.
    private class InsertAction implements ActionListener
    public void actionPerformed(ActionEvent event)
    String input = event.getActionCommand();
    if (start)
    display.setText("");
    start = false;
    display.setText(display.getText() + input);
    This action executes the command that the button
    action string denotes.
    private class CommandAction implements ActionListener
    public void actionPerformed(ActionEvent evt)
    String command = evt.getActionCommand();
    // System.out.println("The value clear"+command);
    if (command.equals("Clear"))
              display.setText("");
              start = false;
    else
    if (start)
    if (command.equals("-"))
    display.setText(command);
    start = false;
    else
    lastCommand = command;
    else
    calculate(Double.parseDouble(display.getText()));
    lastCommand = command;
    start = true;
    Carries out the pending calculation.
    @param x the value to be accumulated with the prior result.
    public void calculate(double x)
    if (lastCommand.equals("+")) result += x;
    else if (lastCommand.equals("-")) result -= x;
    else if (lastCommand.equals("*")) result *= x;
    else if (lastCommand.equals("/")) result /= x;
    else if (lastCommand.equals("=")) result = x;
    display.setText("" + result);
    public void keyTyped(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         int id = e.getID();
         String keyString="";
         System.out.println("The value KeyEvent.KEY_TYPED"+KeyEvent.KEY_TYPED);
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    //System.out.println("The value c"+c);
    if(c=='*' || c=='/' || c=='-'||c=='+' || c=='=')
         start = true;
    else
         start = false;
         keyString = display.getText()+ c ;
         System.out.println("The value keyString"+keyString);
    else {
    calculate(Double.parseDouble(display.getText()));
    start = true;
    display.setText(keyString);
    public void keyPressed(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         String keyString;
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    keyString = "key character = '" + c + "'";
    } else {
    int keyCode = e.getKeyCode();
    keyString = "key code = " + keyCode
    + " ("
    + KeyEvent.getKeyText(keyCode)
    + ")";
    display.setText("keyPressed:::"+keyString);**/
    public void keyReleased(KeyEvent e) {
         //You should only rely on the key char if the event
    //is a key typed event.
         String keyString;
    int id = e.getID();
    if (id == KeyEvent.KEY_TYPED) {
    char c = e.getKeyChar();
    keyString = "key character = '" + c + "'";
    } else {
    int keyCode = e.getKeyCode();
    keyString = "key code = " + keyCode
    + " ("
    + KeyEvent.getKeyText(keyCode)
    + ")";
    display.setText("keyReleased:::"+keyString);**/
    }

    Please state why the question is urgent?
    You where given a suggestion 7 minutes after you posted the question, yet it has been over 2 hours and you have not yet responded indicating whether the suggest helped or not.
    So I gues its really not the urgent after all and therefore I will ignore the question.
    By the way, learn how to use the "Code Formatting Tags" when you post code, so the code you post is actually readable.

  • Scope and Objectives of making java swing scientific calculator

    I am going to write code for java swing scientific calculator..... can any body help me to write scope and objectives of this project.... please please :-(

    If this is for school work, then defining the scope is part of the problem. The only advice I will give you is that you only need to implement what the assignment specifies. It is probably intentionally vague so you can bite off way too much and not finish -- failure should teach you something too.
    I had just such an assignment in my software engineering class in college -- create a cross compiler from X to Y where X and Y where known instruction sets. That was the entire assignment -- plus the instruction sets for X and Y. My team looked at the allotted time and resources availabe and decided to do a minimal implementation.
    We where the only team to complete the assignment and all recieved A's because we accurately implemented the required solution and were able to evaluate the real problem--resource allotment--accurately.
    Each other team tried to add "extras" that would "guarantee" them an A grade. In actuallity it was just a lot more work than they could do though and it hurt them in the long run--No matter how good the work was to the point they had at the end of the semester, each student in the other teams only recieved a B or less grade in the class due to failure on that project. Resource allocation and planning--only you can do that for your team/project.

  • Swing Calculator - Logical errors

    Hello,
    I have a couple of problems with the code below
    one of them is with the setLayout().
    Can anyone give a look to that code and tell me what's going wrong , or help me to make it work ??
    Thanks in advance!
    import java.awt.*;
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Container;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.*;
    public class Calculator extends JFrame implements ActionListener
        public static final int Width = 500;
        public static final int Height = 500;
        private JTextField Board;
        private JButton jbo0, jbo1, jbo2, jbo3, jbo4, jbo5, jbo6, jbo7, jbo8, jbo9,
                        jboAddition, jboSubtraction, jboMultiplication, jboDivision,
                        jboDot, jboLp, jboRp, jboClear, jboResult;
        public static void main(String args[])
        JFrame applet = new Calculator();
        JFrame frame = new JFrame();
        frame.add(frame);
        frame.setSize(Width,Height);
        frame.show();
    public static void main(String args[])
        JFrame outputFrame = new Calculator();
    //panel1.add(allyourstuff);
    //panel1.add(moreofyourstuff);
        outputFrame.setVisible(true);
        public Calculator()
            Container outputPane = this.getContentPane();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setSize(Width, Height);
            outputPane.setLayout(new GridLayout (3, 3));
            Panel panel1 = new Panel();
            this.setDefaultCloseOperation( EXIT_ON_CLOSE );
            Board = new JTextField();
            panel1.add(Board);
            outputPane.add(panel1);
            //panel1.add(jbo0);
            //Numbers
            setLayout(new FlowLayout());
            setFont(new Font("Helvetica", Font.PLAIN, 8));
            JButton jbo0 = new JButton("0");
            jbo0.addActionListener(this);
            panel1.add(jbo0);
            jbo1 = new JButton("1");
            panel1.add(jbo1);
            jbo1.addActionListener(this);
            jbo2 = new JButton("2");
            panel1.add(jbo2);
            jbo2.addActionListener(this);
            jbo3 = new JButton("3");
            panel1.add(jbo3);
            jbo3.addActionListener(this);
            jbo4 = new JButton("4");
            panel1.add(jbo4);
            jbo4.addActionListener(this);
            jbo5 = new JButton("5");
            panel1.add(jbo5);
            jbo5.addActionListener(this);
            jbo6 = new JButton("6");
            panel1.add(jbo6);
            jbo6.addActionListener(this);
            jbo7 = new JButton("7");
            panel1.add(jbo7);
            jbo7.addActionListener(this);
            jbo8 = new JButton("8");
            panel1.add(jbo8);
            jbo8.addActionListener(this);
            jbo9 = new JButton("9");
            panel1.add(jbo9);
            jbo9.addActionListener(this);
            //Math Operations
            jboAddition = new JButton("+");
            panel1.add(jboAddition);
            jboAddition.addActionListener(this);
            jboSubtraction = new JButton("-");
            panel1.add(jboSubtraction);
            jboSubtraction.addActionListener(this);
            jboMultiplication = new JButton("*");
            panel1.add(jboMultiplication);
            jboMultiplication.addActionListener(this);
            jboDivision = new JButton("/");
            panel1.add(jboDivision);
            jboDivision.addActionListener(this);
            //Result etc..
            jboDot = new JButton(".");
            panel1.add(jboDot);
            jboDot.addActionListener(this);
            jboLp = new JButton("(");
            panel1.add(jboLp);
            jboLp.addActionListener(this);
            jboRp = new JButton(")");
            panel1.add(jboRp);
            jboRp.addActionListener(this);
            jboClear = new JButton("C");
            panel1.add(jboClear);
            jboClear.addActionListener(this);
            jboResult = new JButton("=");
            panel1.add(jboResult);
            jboResult.addActionListener(this);
        public void actionPerformed(ActionEvent e)
            if (e.getSource() instanceof JButton)
                JButton buClicked = (JButton) e.getSource();
                if (buClicked == jboClear)
                    boardClear();
                else if(buClicked == jboResult)
                    Calculate();
            else
                Calculate();
        public void UserInput(JButton buClicked)
            String input;
            input = Board.getText();
            if (buClicked == jbo0)
                Board.setText(input + "0");
            if (buClicked == jbo1)
                Board.setText(input + "1");
            if (buClicked == jbo2)
                Board.setText(input + "2");
            if (buClicked == jbo3)
                Board.setText(input + "3");
            if (buClicked == jbo4)
                Board.setText(input + "4");
            if (buClicked == jbo5)
                Board.setText(input + "5");
            if (buClicked == jbo6)
                Board.setText(input + "6");
            if (buClicked == jbo7)
                Board.setText(input + "7");
            if (buClicked == jbo8)
                Board.setText(input + "8");
            if (buClicked == jbo9)
                Board.setText(input + "9");
            if (buClicked == jboAddition)
                Board.setText(input + "+");
            if (buClicked == jboSubtraction)
                Board.setText(input + "-");
            if (buClicked == jboMultiplication)
                Board.setText(input + "*");
            if (buClicked == jboDivision)
                Board.setText(input + "/");
            if (buClicked == jboDot)
                Board.setText(input + ".");
            if (buClicked == jboLp)
                Board.setText(input + "(");
            if (buClicked == jboRp)
                Board.setText(input + ")");
         private void boardClear()
            Board.setText("");
        public void Calculate()
            int counter;
            int numParenthesis = 0;
            int lenInput;
            String calc;
            String Answer = "";
            char NumOther;
            calc = Board.getText();
            lenInput = calc.length();
            for (counter = 0; counter < lenInput; counter++)
                NumOther = calc.charAt(counter);
                if (NumOther == ')')
                    numParenthesis--;
                if (NumOther == '(')
                    numParenthesis++;
                if ((NumOther < '(') || (NumOther > '9') || (NumOther == '.'))
                    Board.setText("Error");
                if (NumOther == '.' && (counter + 1 < calc.length()))
                    for (int k = counter + 1; (k < calc.length()) && ((Character.isDigit(calc.charAt(k))) || ((calc.charAt(k))) == '.'); k++)
                        if (calc.charAt(k) == '.')
                            Board.setText("Error");
            if (numParenthesis != 0)
                Board.setText("Error");
            else
                Answer = Calculate2(calc);
                Board.setText(Answer);
        private String CalculatorImp(String oper1, String oper2, char Oper)
            Double op1, op2;
            double ops1, ops2;
            double ans = 0;
            String result;
            op1 = new Double (oper1);
            op2 = new Double (oper2);
            ops1 = op1.doubleValue();
            ops2 = op2.doubleValue();
            if (Oper == '+')
                ans = ops1 + ops2;
            if (Oper == '-')
                ans = ops1 - ops2;
            if (Oper == '*')
                ans = ops1 * ops2 ;
            if (Oper == '/')
                ans = ops1/ops2;
            result = Double.toString(ans);
            return result;
        private String Calculate2(String process)
            String answer = process;
            String op1 = "";
            String op2 = "";
            char userinput;
            int index = 0;
            int indexL = 0;
            int indexR = 0;
            int numInput = answer.length();
            int numPar = 0;
            int matchPar = 0;
            int indexOp1 = 0;
            int indexOp2 = 0;
            if (answer  != "Error")
                for (index = 0; index < numInput; index++)
                    userinput = answer.charAt(index);
                    if (userinput  == '(')
                        if (matchPar == 0)
                            indexOp1 = index;
                        matchPar++;
                        numPar++;
                    if (userinput == ')')
                        matchPar--;
                        if (matchPar ==0)
                            indexOp2 = index;
                if (indexOp1 + 1 == indexOp2)
                    Board.setText("Error");
                if (answer == "Error"  && numPar > 0)
                    if (indexOp1 == 0)
                        if (indexOp2 == (numInput - 1))
                            if (indexOp1 != indexOp2)
                                answer = Calculate2(answer.substring(indexOp1 + 1, indexOp2));
                    else if (indexOp1 == 0 && indexOp2 > 0)
                        if ((Character.isDigit(answer.charAt(indexOp2 + 1))))
                            Board.setText("Error");
                        else
                            answer = Calculate2(answer.substring(indexOp1 + 1, indexOp2)) + answer.substring(indexOp2 + 1);
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                    else if ((indexOp1 > 0) && (indexOp2 > 0) && (indexOp2 != numInput - 1))
                        if (((Character.isDigit(answer.charAt(indexOp2 + 1 ))) ||  (Character.isDigit(answer.charAt(indexOp1 - 1 ))) ))
                            Board.setText("Error");
                        else
                            answer = answer.substring(0, indexOp1) + Calculate2(answer.substring(indexOp1 + 1, indexOp2)) + answer.substring(indexOp2 + 1);
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                    else if (indexOp2 == numInput - 1 && indexOp1 > 0)
                        if (((Character.isDigit(answer.charAt(indexOp1 - 1)))))
                            Board.setText("Error");
                        else
                            answer = answer.substring(0, indexOp1) + Calculate2(answer.substring(indexOp1 + 1, indexOp2));
                            numPar--;
                            while (numPar != 0)
                                answer = Calculate2(answer);
                                numPar--;
                if (numPar == 0)
                    if (answer != "Error")
                        if (!(Character.isDigit(answer.charAt(0))))
                            if (answer.charAt(0) != '-')
                                if (!(Character.isDigit(answer.charAt(answer.length() - 1))))
                                    Board.setText("Error");
                for (index = 0; index < answer.length() && (answer == "Error"); index++)
                    userinput = answer.charAt(index);
                    if (userinput == '*' || userinput == '/')
                        if (!(Character.isDigit(answer.charAt(index-1))) || (!(Character.isDigit(answer.charAt(index + 1)))))
                            if (answer.charAt(index + 1) != '-')
                                Board.setText("Error");
                        if (answer.charAt(index + 1) == '-')
                            if (!(Character.isDigit(answer.charAt(index + 2))))
                                Board.setText("Error");
                        if (answer == "Error")
                            indexL = index - 1;
                            if (indexL > 2)
                                if ((answer.charAt(indexL - 1)) == '-')
                                    if ((answer.charAt(indexL - 2)) == 'E')
                                        indexL = indexL -2;
                                while ((indexL  > 0) && ((Character.isDigit(answer.charAt(indexL - 2)) || ((answer.charAt(indexL - 1)) == '.') || ((answer.charAt(indexL - 1)) == 'E' ))))
                                    indexL--;
                                if (indexL == 1)
                                    if ((answer.charAt(indexL - 1)) == '-')
                                        indexL--;
                                if (indexL > 2)
                                    if (((answer.charAt(indexL - 1)) == '-') && !(Character.isDigit(answer.charAt(indexL - 2))))
                                            indexL--;
                                op2 = answer.substring(index + 1, indexR + 1);
                    for (index = 0; index < answer.length() && (answer != "Error"); index++)
                        if (index == 0)
                            index = 1;
                    if (index > 0)
                            if (answer.charAt(index + 1) == '-')
                                index = index + 2;
                    userinput = answer.charAt(index);
                    if ((userinput == '+') || (userinput == '-'))
                        if (!(Character.isDigit(answer.charAt(index - 1))))
                            Board.setText("Error");
                        if (!(Character.isDigit(answer.charAt(index + 1))))
                            Board.setText("Error");
                        if ((answer.charAt(index+1) == '-') && (!(Character.isDigit(answer.charAt(index+2)))))
                             Board.setText("Error");
                        if (answer != "Error")
                            indexL = 0;
                            op1 = answer.substring(indexL , index);
                            indexR = index + 1;
                            while((indexR < answer.length()-1) && ((Character.isDigit(answer.charAt(indexR + 1))) || ((answer.charAt(indexR + 1)) == '.') || ((answer.charAt(indexR + 1)) == 'E')))
                                indexR++;
                                if (indexR < answer.length() - 2)
                                        if ((answer.charAt(indexR + 1)) == '-')
                                            indexR++;
                            op2 = answer.substring(index + 1, indexR + 1);
                            answer = CalculatorImp(op1, op2, userinput ) + answer.substring(indexR + 1);
                            index = 0;
            return answer;
    }

    Your UserInput method doesn't seem to get called anywhere.
    You need to sort out the layout - try a vertical box containing the input and horizontal boxes for the button, or a simple grid. If using a GridLayout, the number of rows and column you give in the constructor should
    Move the actual calculation code out into a separate class - you then can test it more easily with a driver which feeds it lots of expressions, and your UI code isn't all mixed up with it.
    It's a convention to use lower case initial letters on variable and method names.
    Your code is very redundant - create one ActionListener which you attach to each your single character button to append the value of that button to the input box, rather than having all those tests, and extract that code into a single method.
    When you add a swing component to another, it keeps a reference to it so it can draw it. You don't need to, unless you want to do something else which it later on.
    Eg:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SwingCalculator extends JFrame {
      public static void main(String args[]) {
        new SwingCalculator().setVisible(true);
      final JTextField board;
      public SwingCalculator () {
        Container outputPane = this.getContentPane();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setFont(new Font("Helvetica", Font.PLAIN, 18));
        setTitle("SwingCalculator");
        outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
        board = new JTextField();
        outputPane.add(board);
        final JPanel buttons = new JPanel();
        buttons.setLayout(new GridLayout (5, 4));
        outputPane.add(buttons);
        // Buttons which append to the board
        addButtons(buttons, "7", "8", "9", "+");
        addButtons(buttons, "4", "5", "6", "-");
        addButtons(buttons, "1", "2", "3", "*");
        addButtons(buttons, ".", "0", "E", "/");
        addButtons(buttons, "(", ")");
        // the C and = buttons have special action listeners
        final JButton cancel = new JButton("C");
        buttons.add(cancel);
        cancel.addActionListener(new ActionListener() {
          public void actionPerformed (ActionEvent event) {
            board.setText("");
        final JButton calculate = new JButton("=");
        buttons.add(calculate);
        // move the expression code to a separate class and call it here
        calculate.addActionListener(new ActionListener() {
          public void actionPerformed (ActionEvent event) {
            try {
              board.setText(ExpressionParser.evaluate(board.getText()));
            } catch (ExpressionParseException ex) {
              board.setText("ERROR");
        pack();
      // adds buttons which, when pressed, append their label to the board
      public void addButtons (JPanel panel, String... labels) {
        for (final String label:labels) {
          JButton button = new JButton(label);
          panel.add(button);
          button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              board.setText(board.getText() + label);
    }

  • GUI Calculator (Swing, BorderLayout, etc.)

    I am a bit of a crossroads and am needing some advice. I am trying to create a Calculator in a Window (GUI) that looks similar to a keypad. I have three files that I am working on but cannot get any of them to compile without errors. I am confused as to what I have left out and/or where I have taken a wrong turn. I will post them below and would greatly appreciate any insight and/or direction as to how to make this work! Also, I have heard from a "birdie" that there may be some problems that occur if the files are compiled out of order....does this make sense to anyone? Thank you in
    advance for any help--Christle
    Constants.java file
    //Christle Chumney
    import java.awt.*;
    public interface Constants
      Color FUNCTION_COLOR = Color.red;
      Color OPERATOR_COLOR = Color.blue;
      Color NUMBER_COLOR = Color.black;
    }calculator.java file
    //Christle Chumney
    import java.awt.*;
    public class Calculator  {
      public static void main(String[] args){
         theApp = new Calculator();
         theApp.init();
      public void init() {
        aWindow = new CalculatorFrame("My Calculator");
        aWindow.setBounds(10, 10, 250, 250);
        aWindow.setVisible(true); }
      private static CalculatorFrame aWindow;
      private static Calculator theApp;
    }calculatorFrame.java file
    //Christle Chumney
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    public class CalculatorFrame extends JFrame implements Constants //, ActionListener
      private Calculator theApp;
      JPanel top, bottom;
      JTextField display;
      JButton button;
      // Constructor
      public CalculatorFrame(String title)
        setTitle(title);  // Set the window title
        this.theApp = theApp;
        JMenuBar swingMenuBar = new JMenuBar();
        JMenu swingMenu = new JMenu("swingMenu");
        JMenuItem swingMenuItem1, swingMenuItem2, swingMenuItem3;
         swingMenuBar.add(swingMenu);
         setJMenuBar(swingMenuBar);
        JMenu applicationMenu = new JMenu("Function");    // Create Application menu
        applicationMenu.setMnemonic('A');                    // Create shortcut
        // Construct the application pull down menu
        exitItem = applicationMenu.add("Exit");                // Add exit item
        exitItem.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK ));
        applicationMenu.add(exitItem);
        menuBar.add(applicationMenu);                        // Add the file menu   
        makeButtons();
      public void makeButtons() {
        BorderLayout border = new BorderLayout();
        Container content = getContentPane();
        content.setLayout(border);
        top = new JPanel(new BorderLayout());
        display = new JTextField("");
        display.setEditable(false);
        display.setBackground(Color.white);
        display.setHorizontalAlignment(display.RIGHT);
        top.add(display);
        bottom = new JPanel();
        GridLayout grid = new GridLayout(5,4,5,5);
        bottom.setLayout(grid);
        bottom.add(button = new JButton("C"));
        button.setForeground(FUNCTION_COLOR);
        bottom.add(button = new JButton("<=="));
        button.setForeground(FUNCTION_COLOR);
        bottom.add(button = new JButton("%"));
        button.setForeground(OPERATOR_COLOR);
        bottom.add(button = new JButton("/"));
        button.setForeground(OPERATOR_COLOR);
        bottom.add(button = new JButton("7"));
        bottom.add(button = new JButton("8"));
        bottom.add(button = new JButton("9"));
        bottom.add(button = new JButton("*"));
        button.setForeground(OPERATOR_COLOR);
        bottom.add(button = new JButton("4"));
        bottom.add(button = new JButton("5"));
        bottom.add(button = new JButton("6"));
        bottom.add(button = new JButton("-"));
        button.setForeground(OPERATOR_COLOR);
        bottom.add(button = new JButton("1"));
        bottom.add(button = new JButton("2"));
        bottom.add(button = new JButton("3"));
        bottom.add(button = new JButton("+"));
        button.setForeground(OPERATOR_COLOR);
        bottom.add(button = new JButton("0"));
        bottom.add(button = new JButton("+/-"));
        bottom.add(button = new JButton("."));
        bottom.add(button = new JButton("="));
        button.setForeground(OPERATOR_COLOR);
         Container content = aWindow.getContentPane();
         content.setLayout(new BorderLayout());
         content.add(top, BorderLayout, NORTH);
         content.add(bottom, BorderLayout, CENTER);
      private JMenuBar menuBar = new JMenuBar();      // Window menu bar
      private JMenuItem exitItem;                       // application menu item 
    }Thanks in advance (again)-
    Christle

    HERE R U .JAVA FILES AND THEY WORK FINE NOW NO ERRORS NOTHING JUST THAT U HAVE TO CODE THE EVENTS OF UR APPLICATION
    ANYOTHER HELP U NEED UR MOST WELCOME
    VIJAY
    // CALCULATORFRAME.JAVA
    //Christle Chumney
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    public class CalculatorFrame extends JFrame implements Constants //,ActionListener
         private Calculator theApp;
         JPanel top, bottom;
         JTextField display;
         JButton button;
    // Constructor
         public CalculatorFrame(String title)
              setTitle(title);
    // Set the window title
              this.theApp = theApp;
              JMenuBar swingMenuBar = new JMenuBar();
              JMenu swingMenu = new JMenu("swingMenu");
              JMenuItem swingMenuItem1, swingMenuItem2, swingMenuItem3;     
              swingMenuBar.add(swingMenu);     
              setJMenuBar(swingMenuBar);
              JMenu applicationMenu = new JMenu("Function");
    // Create Application menu
              applicationMenu.setMnemonic('A');
    // Create shortcut
    // Construct the application pull down menu
              exitItem = applicationMenu.add("Exit");
    // Add exit item           exitItem.setAccelerator(KeyStroke.getKeyStroke('X',Event.CTRL_MASK ));           applicationMenu.add(exitItem);
              menuBar.add(applicationMenu);
    // Add the file menu
              makeButtons();
    public void makeButtons()
         BorderLayout border = new BorderLayout();
         Container content = getContentPane();
         content.setLayout(border);
         top = new JPanel(new BorderLayout());
         display = new JTextField("");
         display.setEditable(false);
         display.setBackground(Color.white);
         display.setHorizontalAlignment(display.RIGHT);
         top.add(display);
         bottom = new JPanel();
         GridLayout grid = new GridLayout(5,4,5,5);
         bottom.setLayout(grid);
         bottom.add(button = new JButton("C"));
         button.setForeground(FUNCTION_COLOR);
    bottom.add(button = new JButton("<=="));
         button.setForeground(FUNCTION_COLOR);
         bottom.add(button = new JButton("%"));
         button.setForeground(OPERATOR_COLOR);
         bottom.add(button = new JButton("/"));
         button.setForeground(OPERATOR_COLOR);
         bottom.add(button = new JButton("7"));
         bottom.add(button = new JButton("8"));
         bottom.add(button = new JButton("9"));
         bottom.add(button = new JButton("*"));
         button.setForeground(OPERATOR_COLOR);
         bottom.add(button = new JButton("4"));
         bottom.add(button = new JButton("5"));
         bottom.add(button = new JButton("6"));
         bottom.add(button = new JButton("-"));
         button.setForeground(OPERATOR_COLOR);
         bottom.add(button = new JButton("1"));
         bottom.add(button = new JButton("2"));
         bottom.add(button = new JButton("3"));
         bottom.add(button = new JButton("+"));
         button.setForeground(OPERATOR_COLOR);
         bottom.add(button = new JButton("0"));
         bottom.add(button = new JButton("+/-"));
         bottom.add(button = new JButton("."));
         bottom.add(button = new JButton("="));
         button.setForeground(OPERATOR_COLOR);     
         Container content1 = this.getContentPane();     
         content.setLayout(new BorderLayout());
         content1.add(top, BorderLayout.NORTH);
         content1.add(bottom, BorderLayout.CENTER);
         private JMenuBar menuBar = new JMenuBar();
    // Window menu bar
         private JMenuItem exitItem;
    // application menu item
    // CALCULATOR.JAVA
    import java.awt.*;
    public class Calculator
    public static void main(String[] args)
    {     theApp = new Calculator();
         theApp.init();
    public void init()
    aWindow = new CalculatorFrame("My Calculator");
    aWindow.setBounds(10, 10, 250, 250);
    aWindow.setVisible(true);
    private static CalculatorFrame aWindow;
    private static Calculator theApp;
    // CONSTANTS.JAVA
    import java.awt.*;
    public interface Constants
    Color FUNCTION_COLOR = Color.red;
    Color OPERATOR_COLOR = Color.blue;
    Color NUMBER_COLOR = Color.black;

  • How to create a calculator by using javax swing

    I try to us Javax swing make some buttons like 0 - 9 then input some numbers by using those number like a calculator. But I only can get numbers no more than 9.
    Please help me.

    How do you store the number the user enters? If it's in a string and the previous value was eg "1" and the user enters "2" you get "12" with a simple concatenation: val += input.
    OTOH, if you work with doubles and the previous value was 1.0 and the user enters 2.0 by pressing the button you get 12.0 by multiplying 1.0 with 10 and adding 2.0: val = 10*val + input.

  • Incompatible in unix? calculating cpu time in swing ?

    I am confused about the fact that when I run my swing program in netbeans on windows xp platform. The buttons have the ability to traverse the focus around using TAB key. But when I run the program in unix, the TAB key has no effect on the focus at all. I really want the TAB key to work !!!
    Also, anyone knows if java has a method to calculate cpu time? I can only use System.currentTimeMillis() to measure the wall clock time. But I will need the actual cpu time spent on that particular thread.
    Can somebody help ? Thanks !!!

    the TAB key has no effect on the focus at all. I
    really want the TAB key to work !!!This is an OS specific thing, not a Java thing
    Also, anyone knows if java has a method to calculate
    cpu time? I can only use System.currentTimeMillis()
    to measure the wall clock time. But I will need theNo. No such method exists. However you can use diagnostic packages like JProbe

  • Calculator applet using swing

    please Help!!!!!
    This thing keeps giving a Null Pointer Exception whenever you click a button it compiles fine and runs ok until a button is clicked.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MyCalculator extends JApplet implements ActionListener {
    private char op = 0;
    private float num1 = 0, num2 = 0, value = 0 ;
    private boolean clearNext = false;
    private JTextField display, textField2;
    private JButton buttonEq, buttonPlus, buttonMinus, buttonMult,buttonCos;
    private JButton buttonDiv,buttonPlusMinus,buttonDec,buttonC,buttonSin;
    private JButton buttonTan;
    private JButton button = new JButton();
    private boolean start = true;
    // create GUI components
    public void init() {
    Container con = getContentPane();
    con.setLayout( new BorderLayout());
    con.setBackground(Color.darkGray);
    //add display display
    JTextField display = new JTextField( "0", 15 );
    display.setBackground(Color.black);
    display.setForeground(Color.red);
    display.setEditable(false);
    JTextField textField2 = new JTextField( " Design and Implementation By Erwin Zeitner" );
    textField2.setBackground(Color.black);
    textField2.setForeground(Color.red);
    textField2.setEditable(false);
    //create numbered buttons
    JButton button0 = new JButton("0" );
    button0.setBackground(Color.blue);
    JButton button1 = new JButton( "1" );
    button1.setBackground(Color.blue);
    JButton button2 = new JButton( "2" );
    button2.setBackground(Color.blue);
    JButton button3 = new JButton( "3" );
    button3.setBackground(Color.blue);
    JButton button4 = new JButton( "4" );
    button4.setBackground(Color.blue);
    JButton button5 = new JButton( "5" );
    button5.setBackground(Color.blue);
    JButton button6 = new JButton( "6" );
    button6.setBackground(Color.blue);
    JButton button7 = new JButton( "7" );
    button7.setBackground(Color.blue);
    JButton button8 = new JButton( "8" );
    button8.setBackground(Color.blue);
    JButton button9 = new JButton( "9" );
    button9.setBackground(Color.blue);
    //create function buttons
    JButton buttonC = new JButton( "clear" );
    buttonC.setBackground(Color.green);
    JButton buttonPlus = new JButton( "+" );
    buttonPlus.setBackground(Color.green);
    JButton buttonMinus = new JButton( "-" );
    buttonMinus.setBackground(Color.green);
    JButton buttonMult = new JButton( "*" );
    buttonMult.setBackground(Color.green);
    JButton buttonDiv = new JButton( "/" );
    buttonDiv.setBackground(Color.green);
    JButton buttonSin = new JButton( "Sin" );
    buttonSin.setBackground(Color.green);
    JButton buttonCos = new JButton( "Cos" );
    buttonCos.setBackground(Color.green);
    JButton buttonTan = new JButton( "Tan" );
    buttonTan.setBackground(Color.green);
    JButton buttonDec = new JButton( "." );
    buttonDec.setBackground(Color.blue);
    JButton buttonEq = new JButton( "=" );
    buttonEq.setBackground(Color.orange);
    JButton buttonPlusMinus = new JButton( "+/-" );
    buttonPlusMinus.setBackground(Color.blue);
    //create a panel for each row
    JPanel row1 = new JPanel();
    row1.setBackground(Color.darkGray);
    JPanel row2 = new JPanel();
    row2.setBackground(Color.darkGray);
    JPanel row3 = new JPanel();
    row3.setBackground(Color.darkGray);
    JPanel row4 = new JPanel();
    row4.setBackground(Color.darkGray);
    JPanel row5 = new JPanel();
    row5.setBackground(Color.darkGray);
    JPanel row6 = new JPanel();
    row6.setBackground(Color.darkGray);
    JPanel row7 = new JPanel();
    row7.setBackground(Color.darkGray);
    //create panel for rows and set layout
    JPanel p = new JPanel();
    p.setLayout(new GridLayout( 7,1,0,5 ));
    p.setBackground(Color.darkGray);
    //set layout for rows
    GridLayout grid = new GridLayout(1,4,5,0);
    //add buttons & display field to rows
    row1.setLayout(grid);
    row1.add(display);
    //add row to panel
    p.add(row1);
    row2.setLayout(grid);
    buttonC.addActionListener(this);
    row2.add(buttonC);
    buttonSin.addActionListener(this);
    row2.add(buttonSin);
    buttonCos.addActionListener(this);
    row2.add(buttonCos);
    buttonTan.addActionListener(this);
    row2.add(buttonTan);
    //add row to panel
    p.add(row2);
    row3.setLayout(grid);
    button7.addActionListener(this);
    row3.add(button7);
    button8.addActionListener(this);
    row3.add(button8);
    button9.addActionListener(this);
    row3.add(button9);
    buttonPlus.addActionListener(this);
    row3.add(buttonPlus);
    //add row to panel
    p.add(row3);
    row4.setLayout(grid);
    button4.addActionListener(this);
    row4.add(button4);
    button5.addActionListener(this);
    row4.add(button5);
    button6.addActionListener(this);
    row4.add(button6);
    buttonMinus.addActionListener(this);
    row4.add(buttonMinus);
    //add row to panel
    p.add(row4);
    row5.setLayout(grid);
    button1.addActionListener(this);
    row5.add(button1);
    button2.addActionListener(this);
    row5.add(button2);
    button3.addActionListener(this);
    row5.add(button3);
    buttonMult.addActionListener(this);
    row5.add(buttonMult);
    //add row to panel
    p.add(row5);
    row6.setLayout(grid);
    button0.addActionListener(this);
    row6.add(button0);
    buttonDec.addActionListener(this);
    row6.add(buttonDec);
    buttonPlusMinus.addActionListener(this);
    row6.add(buttonPlusMinus);
    buttonDiv.addActionListener(this);
    row6.add(buttonDiv);
    //add row to panel
    p.add(row6);
    row7.setLayout(grid);
    buttonEq.addActionListener(this);
    row7.add(buttonEq);
    //add row to panel
    p.add(row7);
    // add panel and textField2 to the container
    con.add(p,BorderLayout.CENTER);
    con.add(textField2,BorderLayout.SOUTH);
    public void actionPerformed(ActionEvent e) {
    String buttonPressed = e.getActionCommand();
    try {
    if (buttonPressed.equals( "+/-" )) {
    value = getValue(display.getText());
    value *= -1;
    clearOutput();
    addToOutput("" + value );
    else switch ( buttonPressed.charAt(0) ) {
    case '+':
    case '-':
    case '*':
    case '/':
    buttonEq.setEnabled(true);
    buttonPlus.setEnabled(false);
    buttonMinus.setEnabled(false);
    buttonMult.setEnabled(false);
    buttonDiv.setEnabled(false);
    num1 = getValue(display.getText());
    op = buttonPressed.charAt(0);
    clearNext = true;
    break;
    case '=':
    buttonEq.setEnabled(true);
    buttonPlus.setEnabled(true);
    buttonMinus.setEnabled(true);
    buttonMult.setEnabled(true);
    buttonDiv.setEnabled(true);
    getResult();
    num1 = getValue(display.getText());
    op = 0 ;
    clearNext = true;
    break;
    case 'C':
    float num1 = getValue(display.getText());
    op = buttonPressed.charAt(0);
    getResult();
    clearNext = false;
    break;
    case 'S':
    num1 = getValue(display.getText());
    op = buttonPressed.charAt(0);
    getResult();
    clearNext = false;
    break;
    case 'T':
    num1 = getValue(display.getText());
    op = buttonPressed.charAt(0);
    getResult();
    clearNext = false;
    break;
    case 'c':
    clearOutput();
    op = 0 ;
    num1 = (float) 0 ;
    break;
    default:
    if (clearNext) {
    clearOutput();
    clearNext = false;
    addToOutput(buttonPressed);
    catch( Exception exception) {
    System.err.println(exception.toString());
    public void getResult() {
    float num2 = getValue(display.getText());
    switch (op) {
    case '+':
    num1 += num2;
    break;
    case '-':
    num1 -= num2;
    break;
    case '*':
    num1 *= num2;
    break;
    case '/':
    if (num2 != 0)
    num1 /= num2;
    else
    num1 = 0;
    break;
    case 'C':
    Math.cos(num1);
    break;
    case 'S':
    Math.sin(num1);
    break;
    case 'T':
    Math.tan(num1);
    break;
    clearOutput();
    addToOutput( "" + num1 );
    clearNext = true;
    public void addToOutput( String buttonPressed) {
    String newOutput = display.getText();
    if (buttonPressed.equals(".")) {
    if (newOutput.indexOf(".") == -1)
    newOutput += ".";
    else
    newOutput += buttonPressed;
    int newLength = newOutput.length();
    display.setText(newOutput);
    public void clearOutput() {
    try{
    display.setText( "" );
    catch(Exception c) {
    System.err.println(c.toString());
    public float getValue(String arg) {
    if (arg.equals("."))
    arg = "0";
    Float f = Float.valueOf(arg);
    return f.floatValue();

    I have found your error please change this to the below one
    //add display display
    JTextField display = new JTextField( "0", 15 );
    display.setBackground(Color.black);
    display.setForeground(Color.red);
    display.setEditable(false);
    //add display display
    display = new JTextField( "0", 15 );
    display.setBackground(Color.black);
    display.setForeground(Color.red);
    display.setEditable(false);
    if you noticed, you declared the display as a global variable but did not intialized it that is why u get NullPointerException.
    By declaring JTextField display again in a method it only belong to that method which is init()
    The other textfield also have to be changed if you wish to access it from elsewhere(ex. textfield2 )
    Thanks
    Joey

  • PL/SQL and Java Swing interface

    Everybody in this forum knows that Oracle is the best database around
    with many functionalities, stability, performance, etc. We also know
    that PL/SQL is a great language to manipulate information directly
    in the database with many built in functions, OOP capability,
    transaction control, among other features. Today an application that
    manipulates information, which needs user interface, requires components
    to be developed using different technologies and normally running in
    different servers or machines. For example, the interface is done using
    a dynamic HTML generator like JSP, PHP, PL/SQL Web Toolkit, etc.
    This page is executed in an application server like Oracle iAS or
    Tomcat, just to name two, which in turn access a database like Oracle to
    build the HTML. Also rich clients like Java applets require an intermediate
    server to access the database (through servlets for example) although
    it is possible to access the database directly but with security issues.
    Another problem with this is that complexity increases a lot, many
    technologies, skills and places to maintain code which leads to a greater
    failure probability. Also, an application is constantly evolving, new
    calculations are added, new tables, changed columns. If you have an
    application with product code for example and you need to increase its
    size, you need to change it in the database, search for all occurrences
    of it in the middle-tier code and perhaps adjust interfaces. Normally
    there is no direct dependency among the tier components. On another
    issue, many application interfaces today are based on HTML which doesn't
    have interactive capabilities like rich-client interfaces. Although it
    is possible to simulate many GUI widgets with JavaScript and DHTML, it is
    far from the interactive level we can accomplish in rich clients like
    Java Swing, Flash MX, Win32, etc. HTML is also a "tag-based" language
    originally created to publish documents so even small pages require
    many bytes to be transmitted, far beyond of what we see on the screen.
    Even in fast networks you have a delay time to wait the page to be
    loaded. Another issue, the database is in general the central location
    for all kinds of data. Most applications relies on it for security,
    transaction and availability. My proposal is to use Oracle as the
    central location for interface, processing and data. With this approach
    we can create not only the data manipulation procedures in the database,
    but procedures that also control and manage user interfaces. Having
    a Oracle database as the central location for all components has many
    advantages:
    - Unique point of maintenance, backup and restore
    - Integrated database security
    - One language for everything, PL/SQL or Java (even both if desired)
    - Inherited database cache, transaction and processing optimizations
    - Direct access to the database dictionary
    - Application runs on Oracle which has support for many platforms.
    - Transparent use of parallel processing, clusters and future
    background technologies
    Regarding the interface, I already created a Java applet renderer
    which receives instructions from the database on how to create GUI
    objects and how to respond to events. The applet is only 8kb and can
    render any Swing or AWT object/event. The communication is done
    through HTTP or HTTPS using Oracles's MOD_PLSQL included in the Apache
    HTTP server which comes with the database or application server (iAS).
    I am also creating a database framework and APIs in PL/SQL to
    create and manipulate the client interface. The applet startup is
    very fast because it is very small, you don't need to download large
    classes with the client interface. Execution is done "on-demand"
    according to instructions received from the database. The instructions
    are very optimized in terms of network bandwidth and based on preliminary
    tests it can be up to 1/10 of a similar HTML screen. Less network usage
    means faster response and means that even low speed connections will
    have a good performance (a future development can be to use this in
    wireless devices like PDAs e even cell phones, just an idea for now).
    The applet can also be executed standalone by using Java Web Start.
    With this approach no business code, except the interface, is executed
    on the client. This means that alterations in the application are
    dynamically reflected in the client, no need to "re-download" the
    application. Events are transmitted when required only so network
    usage is minimized. It is also possible to establish triggering
    events to further reduce network usage. Since the protocol used is
    HTTP (which is stateless), the database framework I am creating will
    be responsible to maintain the state of connections, variables, locks
    and session information, so the developer don't need to worry about it.
    The framework will have many layers, from communication up to
    application so there will be pre-built functions to handle queries,
    pagination, lock, mail, log, etc. The final objective is to have a
    rich client application integrated into the database with minimum
    programming and maintenance requirements, not forgetting customization
    capabilities. Below is a very small example of what can de done. A
    desktop with two windows, each window with two fields, a button with an
    image to switch the values, and events to convert the typed text when
    leaving the field or double-clicking it. The "leave" event also has an
    optimization to only be triggered when the text changes. I am still
    developing the framework and adjusting the renderer but I think that all
    technical barriers were transposed by now. The framework is still in
    the early stages, my guess is that only 5% is done so far. As a future
    development even an IDE can be created so we have a graphical environment
    do develop applications. I am willing to share this with the PL/SQL
    community and listen to ideas and comments.
    Example:
    create or replace procedure demo1 (
    jre_version in varchar2 := '1.4.2_01',
    debug_info in varchar2 := 'false',
    compress_buffer in varchar2 := 'false',
    optimize_buffer in varchar2 := 'true'
    ) as
    begin
    interface.initialize('demo1_init','JGR Demo 1',jre_version,debug_info,compress_buffer,optimize_buffer);
    end;
    create or replace procedure demo1_init as
    begin
    toolkit.initialize;
    toolkit.create_icon('icon',interface.global_root_url||'img/switch.gif');
    toolkit.create_internal_frame('frame1','Frame 1',50,50,300,136);
    toolkit.create_label('frame1label1','frame1',10,10,50,20,'Field 1');
    toolkit.create_label('frame1label2','frame1',10,40,50,20,'Field 2');
    toolkit.create_text_field('frame1field1','frame1',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
    toolkit.create_text_field('frame1field2','frame1',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
    toolkit.set_text_field_event('frame1field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
    toolkit.set_text_field_event('frame1field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
    toolkit.set_text_field_event('frame1field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
    toolkit.set_text_field_event('frame1field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
    toolkit.create_button('button1','frame1',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
    toolkit.set_button_event('button1',toolkit.action_performed_event,'demo1_switch_fields(''frame1field1'',''frame1field2'')','frame1field1:'||toolkit.get_text_method||',frame1field2:'||toolkit.get_text_method);
    toolkit.create_internal_frame('frame2','Frame 2',100,100,300,136);
    toolkit.create_label('frame2label1','frame2',10,10,50,20,'Field 1');
    toolkit.create_label('frame2label2','frame2',10,40,50,20,'Field 2');
    toolkit.create_text_field('frame2field1','frame2',50,10,230,20,'Field 1','Field 1',focus_event=>true,mouse_event=>true);
    toolkit.create_text_field('frame2field2','frame2',50,40,230,20,'Field 2','Field 2',focus_event=>true,mouse_event=>true);
    toolkit.set_text_field_event('frame2field1',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 1','false');
    toolkit.set_text_field_event('frame2field2',toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,'FIELD 2','false');
    toolkit.set_text_field_event('frame2field1',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 1','false');
    toolkit.set_text_field_event('frame2field2',toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,'field 2','false');
    toolkit.create_button('button2','frame2',10,70,100,25,'Switch','Switch the values of "Field 1" and "Field 2"','S','icon');
    toolkit.set_button_event('button2',toolkit.action_performed_event,'demo1_switch_fields(''frame2field1'',''frame2field2'')','frame2field1:'||toolkit.get_text_method||',frame2field2:'||toolkit.get_text_method);
    end;
    create or replace procedure demo1_set_upper as
    begin
    toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,upper(interface.array_event_value(1)));
    toolkit.set_text_field_event(interface.global_object_name,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
    end;
    create or replace procedure demo1_set_lower as
    begin
    toolkit.set_string_method(interface.global_object_name,toolkit.set_text_method,lower(interface.array_event_value(1)));
    toolkit.set_text_field_event(interface.global_object_name,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
    end;
    create or replace procedure demo1_switch_fields (
    field1 in varchar2,
    field2 in varchar2
    ) as
    begin
    toolkit.set_string_method(field1,toolkit.set_text_method,interface.array_event_value(2));
    toolkit.set_string_method(field2,toolkit.set_text_method,interface.array_event_value(1));
    toolkit.set_text_field_event(field1,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(2)),'false');
    toolkit.set_text_field_event(field2,toolkit.focus_lost_event,'demo1_set_upper',toolkit.get_text_method,upper(interface.array_event_value(1)),'false');
    toolkit.set_text_field_event(field1,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(2)),'false');
    toolkit.set_text_field_event(field2,toolkit.mouse_double_clicked_event,'demo1_set_lower',toolkit.get_text_method,lower(interface.array_event_value(1)),'false');
    end;

    Is it sound like Oracle Portal?
    But you want to save a layer 9iAS.
    Basically, that was the WebDB.(Oracle changed the name to Portal when version 3.0)
    Over all, I agree with you.
    &gt;&gt;Having a Oracle database as the central location for all components has many
    &gt;&gt;advantages:
    &gt;&gt;
    &gt;&gt;- Unique point of maintenance, backup and restore
    &gt;&gt;- Integrated database security
    &gt;&gt;- One language for everything, PL/SQL or Java (even both if desired)
    &gt;&gt;- Inherited database cache, transaction and processing optimizations
    &gt;&gt;- Direct access to the database dictionary
    &gt;&gt;- Application runs on Oracle which has support for many platforms.
    &gt;&gt;- Transparent use of parallel processing, clusters and future
    &gt;&gt;background technologies
    I would like to build 'ZOPE' inside Oracle DB as a back-end
    Using Flash MX as front-end.
    Thomas Ku.

  • Java Newbie needs help with multi method dialog calculator

    Our example for the unit was the example below... we now must create a 5 method program for a calculator... 1 main method and 4 for the standard operations(+ - * /). It is supposed to utilize Swing for graphics/dialog boxes that ask you for the operation you would like to use(if statements based on which operation they enter), and a prompt that asks you separately for the 2 numbers used.... anyone feel like drawing this skeleton out? I am in class right now and none of my neighbors can figure it out either....
    import javax.swing.JOptionPane;
    public class Payroll
         public static void main(String[] args)
         String name;         //the user's name
         String inputString;  //holds input
         int hours;           //hours worked
         double payRate;      //hourly pay wage
         double grossPay;     //total pay
         //getUser
         name = JOptionPane.showInputDialog("What is your name?");
         //getHours
         inputString = JOptionPane.showInputDialog("How many hours did you work?");
         hours = Integer.parseInt(inputString);
         //getRate
         inputString = JOptionPane.showInputDialog("What is your hourly pay rate?");
         payRate = Double.parseDouble(inputString);
         //setGross
         grossPay = payRate * hours;
         //showGross
         JOptionPane.showMessageDialog(null, "Hello " + name + ". Your gross pay is: " + grossPay); 
         //End
         System.exit(0);
    }

    import javax.swing.JOptionPane;
    public class CalcDiag
         public static void main(String[] args)
         String operation;
         String inputString;
         double num1, num2, total=0;
         inputString = JOptionPane.showInputDialog("What is your first number?");
         num1 = Double.parseDouble(inputString);
         inputString = JOptionPane.showInputDialog("What is your second number?");
         num2 = Double.parseDouble(inputString);
         inputString = JOptionPane.showInputDialog("Please indicate which operation you would like to use: A,S,M,D ?");
         operation = inputString;
         if (operation.equals("A"))
              total = getAdd(num1, num2);
         if (operation.equals("S"))
              total = getSub(num1, num2);
         if (operation.equals("M"))
              total = getMult(num1, num2);
         if (operation.equals("D"))
              total = getDiv(num1, num2);
         JOptionPane.showMessageDialog(null,"Total = "+total);
         System.exit(0);
    public static double getAdd(double x, double y)
              return x+y;
    public static double getSub(double x,double y)
              return x-y;
    public static double getMult(double x, double y)
              return x*y;
    public static double getDiv(double x, double y)
              return x/y;
    }your welcome

  • URGENT:problem with memory using swing component

    We use Java SDK 1.4.0-b92 on a Sun Blade Machine with Solaris 8 Operating System.
    We developed a software with a GUI (JFame, JInternalFrame) which have to be refreshed in precise moments and any time we do it there is a big loss of memory(not the Java Virtual Machine Memory but the system memory, see it with the command "vmstat"). It seems that memory isn't released even if we close one or more of the JInternalFrame/JFrame.
    This is a part of our example code which refresh some JTextArea every ten seconds,with the content of a text File called "text.txt" :
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.util.*;
    public class MainFrame extends JFrame {
    static JDesktopPane desktop = new JDesktopPane();
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu();
    JMenuItem aggiungi = new JMenuItem();
    int openFrameCount = 0;
    public MainFrame (){
    try{
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    desktop.setBorder(BorderFactory.createLoweredBevelBorder());
    this.setContentPane(desktop);
    Dimension screenSize= Toolkit.getDefaultToolkit().getScreenSize();
    this.setBounds(0, 0, screenSize.width, screenSize.height);
    this.setTitle("Main Frame Prova");
    this.setLocation(0,0);
    this.setVisible(true);
    menu.setText("apri frame");
    aggiungi.setText("Apri");
    aggiungi.addActionListener(new ActionListener () {
    public void actionPerformed(ActionEvent e){
    createFrame();
    menu.add(aggiungi);
    menuBar.add(menu);
    this.setJMenuBar(menuBar);
    catch (Exception e) {e.printStackTrace();}
    private void createFrame (){
    try{
    NsJInternalFrame frame = new NsJInternalFrame("Frame Interno", true, true, true, true);
    openFrameCount++;
    System.out.println("Frame aperti: "+openFrameCount);
    frame.setVisible(true);
    desktop.add(frame);
    frame.setSelected(true);
    frame.setPreferredSize(new Dimension(400,500));
    frame.setSize(new Dimension(400,500));
    finalize();
    catch (Exception e) {e.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    protected void processWindowEvent (WindowEvent e){
    try{
    super.processWindowEvent(e);
    if (e.getID()== WindowEvent.WINDOW_CLOSING) {
    finalize();
    System.exit(0);
    catch (Exception ex) {ex.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    public static void main (String argv[]){
    try {
    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
    MainFrame mf = new MainFrame();
    while (true){
    Thread.sleep(10000);
    aggiornaTesto();
    Runtime run = Runtime.getRuntime();
    System.out.println("***********************************************************");
    System.out.println("* Memoria Totale "+run.totalMemory()/1000+" *");
    System.out.println("* Memoria Massima occupabile "+run.maxMemory()/1000+" *");
    System.out.println("* *");
    System.out.println("* --------------------------------------------------------- *");
    System.out.println("* *");
    System.out.println("* Memoria Libera "+run.freeMemory()/1000+" *");
    System.out.println("* *");
    System.out.println("***********************************************************");
    System.runFinalization();
    System.gc();
    catch (Exception e) {e.printStackTrace();}
    private static void aggiornaTesto(){
    JInternalFrame[] frameAperti = desktop.getAllFrames();
    for (int i=0; i<frameAperti.length; i++)
    ((NsJInternalFrame)frameAperti).inizializeText();
    System.out.println("----- "+new Date()+" / Aggiornato testo------");
    System.runFinalization();
    System.gc();
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import java.io.*;
    public class NsJInternalFrame extends JInternalFrame {
    JTextArea textArea=new JTextArea();
    public NsJInternalFrame (String title, boolean resizable, boolean closeable, boolean maximizable, boolean iconifiable){
    super (title, resizable, closeable, maximizable, iconifiable);
    disableEvents (AWTEvent.WINDOW_EVENT_MASK);
    JScrollPane scroll;
    scroll=new JScrollPane(textArea);
    this.setContentPane(scroll);
    this.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
    inizializeText();
    public void inizializeText(){
    try{
    RandomAccessFile raf = new RandomAccessFile("text.txt", "r");
    String text = new String(), line = new String();
    while (true) {
    line = raf.readLine();
    if (line==null) break;
    text= text+line;
    textArea.setText(text);
    finalize();
    raf.close();
    catch (Exception e) {e.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    public void dispose (){
    try{
    finalize();
    super.dispose();
    catch (Exception e) {e.printStackTrace();}
    catch (Throwable t) {t.printStackTrace();}
    text.txt
    HELLO HELLO HELLO
    Help Us Please!!
    [email protected]
    [email protected]

    Yes I'm still following the thread.
    Like i said i only have ovi maps running with PhoNetInfo and even today i tested it again. I managed by changing some settings to get 50MB of free RAM when the phone is idle.
    I changed the amount of allowed RAM to be used by ovi maps to the minimum (10%). This time i had 40MB of free ram before calculating the root (again more or less 600km) without tolls and the fastest root. i continued with PhoNetInfo on and following the value of free RAM and they kept falling till i get again the low memory error.
    I tried then a "solution" that i got from nokia that stated to change the configuration of the internet to online, and it worked perfectly. But i don't think this is a solution since i can't have my phone always connected to the internet. I don't know is where i can suggest that nokia try to solve this problem but already sent an email to the client support stating this.
    I don't think i can install a later version of ovimaps since it comes pre-installed on the phone and i don't see where i can uninstall it and where to find the earlier versions.
    But thanks for the reply,

Maybe you are looking for

  • URGENT!restrict user frm edit a field data (allow create) in apx applicatn

    hi, I have a table with 3 columns say col1 primary key col2 col3 i'm filling my col1 with a berfore insert trigger i have built an apex application with a report and form page on above table. my end user can create records through the application for

  • Replies to Mail with Attachments in them

    I have a question about replies I've been getting. When I email with an attachment enclosed the recipient gets the email and the attachments and then replies back. A lot of the time(in leopard) the attachments I sent are visible in the replied messag

  • Java Servlet/Linux issues

    Hi- I use an applet that works fine on Windows but fails on Linux. It stops on the 'Loading Applet' screen. I've tested it in Mozilla, Netscape and KConqueror, all with the same result. I'm guessing it has something to do with the applet making an ex

  • Unable to refresh database after forced stop of the business rule

    Hello, Experts! I am currently testing and tuning performance of business rules in Hyperion Planning 9.3.1. I launched a business rule in EAS Console that was running way too long so I decided to stop it manually. But after this manual stop when I tr

  • Database migrating to secondary server

    I have 3 servers in my Exchange 2013 deployment with 2 being the primary database holders for my 2 active databases and the 3rd server being a failover for either.  One of my databases is now activating itself on the failover even after I manually ac