• (3 Pages)
  • +
  • 1
  • 2
  • 3

Creating a Calculator using JFrame Rate Topic: ***** 5 Votes

#16 scottit  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 16-November 13

Posted 16 November 2013 - 12:54 AM

Hi,
In the method getResult(), I don't understand why do you need the code below?
when I remove it, the result is still the same, for example -9+8=-1

View Postschutzzz, on 27 May 2013 - 04:49 PM, said:

String temp0 = Double.toString(temporary[0]); //necessary string for text of first temp
String temp1 = Double.toString(temporary[1]); //necessary string for text of second temp
try {
if(temp0.contains("-")) { //if first string contains -
String[] temp00 = temp0.split("-", 2); //split into two strings at -
temporary[0] = (Double.parseDouble(temp00[1]) * -1); //puts string back in double with the real value.
}
if(temp1.contains("-")) { // same as above with second temporary
String[] temp11 = temp1.split("-", 2);
temporary[1] = (Double.parseDouble(temp11[1]) * -1);
}
} catch(ArrayIndexOutOfBoundsException e) {
}

Was This Post Helpful? 0
  • +
  • -

#17 dschof41  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-November 13

Posted 20 November 2013 - 12:24 PM

When I try to run the program to make sure the buttons and layout are working I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at NewCalculator.<init>(NewCalculator.java:52)
at NewCalculator.main(NewCalculator.java:101)

There seems to be a problem with my main method even though all it contains is

public static void main(String[] args) {
// TODO Auto-generated method stub
NewCalculator n = new NewCalculator();
}

Any idea why would be great.
Was This Post Helpful? 0
  • +
  • -

#18 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 136
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Posted 21 November 2013 - 04:45 AM

Quote

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at NewCalculator.<init>(NewCalculator.java:52)
at NewCalculator.main(NewCalculator.java:101)


I can't tell you the exact fix without seeing your source code, however an ArrayIndexOutOfBoundsException is thrown when you try to access an index that is either negative or greater than the size of the array itself. If you post your code I can figure out the problem though.

Quote

There seems to be a problem with my main method even though all it contains is


What's the problem with the main method? Looks fine to me.
Was This Post Helpful? 0
  • +
  • -

#19 scottit  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 16-November 13

Posted 21 November 2013 - 06:11 AM

Hi,
I have a small problem with JTextArea display.
I use below command to align text right-to-left.
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

If the string ends with one of following special characters such as ".", "/", "!",
when I call display.setText(str), it's display in reversed order,
for example:

display.setText("0."); // --> ".0"
display.setText("one/"); // --> "/one"

other cases are ok, display.setText("0.2") // --> "0.2" - OK

Anybody can help me?
Thank you,
Was This Post Helpful? 0
  • +
  • -

#20 dschof41  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-November 13

Posted 21 November 2013 - 01:55 PM

View Postschutzzz, on 21 November 2013 - 04:45 AM, said:

Quote

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
at NewCalculator.<init>(NewCalculator.java:52)
at NewCalculator.main(NewCalculator.java:101)


I can't tell you the exact fix without seeing your source code, however an ArrayIndexOutOfBoundsException is thrown when you try to access an index that is either negative or greater than the size of the array itself. If you post your code I can figure out the problem though.

Quote

There seems to be a problem with my main method even though all it contains is


What's the problem with the main method? Looks fine to me.

Thanks for the reply, I fixed it right after I posted the question, just didn't see a way to take it down. It was just a typo in one of the for loops.
If you wanted to add another text field that stores the equation being solved by the calculator next to the text field where the solution is displayed, like a graphing calculator does, how would you go about doing that?
Thanks!
Was This Post Helpful? 0
  • +
  • -

#21 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 136
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Posted 21 November 2013 - 06:21 PM

I'm going to take you through the process of adding the second text area first. You'll have to change the first index of the width dimension array presumably to cut it in half(so it'll be 150), since we have two text areas. Initialize a new JTextArea, say we'll call it displayResult, with the same parameters. Now you'll probably want to fix something on the display side, because we'll want our equation aligned to the left presumably.

display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);



So this line we will want to change to the new text area we just created, displayResult. Make sure to follow the font, and the user can't type into the text area, and set the size to the same as the other display and we'll have this.

JTextArea displayResult = new JTextArea(1,20);

Constructor { //All of this is in the constructor with the other display settings.
    displayResult.setFont(font);
    displayResult.setEditable(false);
    displayResult.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    displayResult.setPreferredSize(displayDimension);
}



Make sure to also add the displayResult text area to the first row,

row[0].add(displayResult);



Now we have a FlowLayout set to the first row. We'll want to change that to a GridLayout. So where we added,

FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);



we'll need to change that up a little bit. We want two components on the same row with a small gap in pixels between them.

GridLayout f1 = new GridLayout(1,2,5,1); //1 Row of Components, 2 Columns, 5px width in between, and 1px height in between.



If you run the program now you'll see that it has the two text areas displayed next to each other. now for modifying the program to how you'd like it.


Running through our program we'll see that in the clear method, we'll need to add below,

display.setText("");



a line for our displayResult which will be the same.

In our getSqrt method, you'll make a few modifications like so,

double value = Math.sqrt(Double.parseDouble(display.getText()));
display.setText("√" + display.getText());
displayResult.setText(Double.toString(value));



Last but not least, modify the getResult method. Modify the try/catch, like so

        try {
            if(function[2] == true) {
                display.setText(temporary[0] + " * " + temporary[1]); //add this
                result = temporary[0] * temporary[1];
            }
            else if(function[3] == true) {
                display.setText(temporary[0] + " / " + temporary[1]); //add this
                result = temporary[0] / temporary[1];
            }
            else if(function[0] == true) {
                display.setText(temporary[0] + " + " + temporary[1]); //add this
                result = temporary[0] + temporary[1];
            }
            else if(function[1] == true) {
                display.setText(temporary[0] + " - " + temporary[1]); //add this
                result = temporary[0] - temporary[1];
            }
            displayResult.setText(Double.toString(result)); //display -> displayResult
            for(int i = 0; i < 4; i++)
                function[i] = false;
        } catch(NumberFormatException e) {
        }



That should work. Let me know if you have any problems with this.

View Postscottit, on 21 November 2013 - 01:11 PM, said:

Hi,
I have a small problem with JTextArea display.
I use below command to align text right-to-left.
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

If the string ends with one of following special characters such as ".", "/", "!",
when I call display.setText(str), it's display in reversed order,
for example:

display.setText("0."); // --> ".0"
display.setText("one/"); // --> "/one"

other cases are ok, display.setText("0.2") // --> "0.2" - OK

Anybody can help me?
Thank you,


Is this directly related to this tutorial at all? Special characters aren't really being outputted in this tutorial in the result so I don't know why you'd have, . / !. If not you can check out the Java Help forum and post a thread there.
Was This Post Helpful? 0
  • +
  • -

#22 scottit  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 16-November 13

Posted 22 November 2013 - 01:58 AM

Hi schutzzz,
Thank for details,
actually I don't have problem with the Calculator example, I just meet a small difficulty with JTextArea,
if I align the text on the right, like in below code, displaying string there is no problem EXCEPT:
when the last character of string is one of the following chars ".", "!", "/"

for example, I'm inputing a decimal, say 6.9
- first, it displays "6"
- then, it displays "6." <----- problem in this step, it shows ".6"
- last, it displays "6.9" <----- now it's ok, "6.9"

That's my problem.
Do you have any idea?
Thanks

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

//public class Calculator extends JFrame implements ActionListener {
public class Calculator extends JFrame{
JPanel[] row = new JPanel[2];
int[] dimW = {300,55,70,120};
int[] dimH = {35, 40, 90};
Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
Dimension enterButDimension = new Dimension(dimW[2], dimH[2]);
Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);

JTextArea display = new JTextArea(2,10);

Font font = new Font("arial", Font.PLAIN, 14);
Font displayFont = new Font("arial", Font.BOLD, 14);

Calculator() {
super("Calculator"); // call constructor of super class, first line
setDesign();
setSize(380, 300);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(5,5);
setLayout(grid);

FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
row[0] = new JPanel();
row[0].setLayout(f1);

display.setFont(displayFont);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setAlignmentX(Component.RIGHT_ALIGNMENT);
display.setPreferredSize(displayDimension);

//display.setText("0"); // OK
//display.setText("0.9"); // OK "0.9"
//display.setText("0."); // not OK ".0" it should be "0."
display.setText("6."); // not OK ".6" it should be "6."
//display.setText("6.0"); // OK "6.0"

row[0].add(display);
add(row[0]);



setVisible(true);
}

public final void setDesign() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}

public static void main(String[] arguments) {
Calculator c = new Calculator();
}

}
Was This Post Helpful? 0
  • +
  • -

#23 codeNtheory  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 14-February 13

Posted 26 November 2013 - 10:41 AM

Great tutorial, I am new to java, and was just wondering where you are getting the square root symbol and plus minus symbol for the buttonString array? Thanks again for this tutorial!
Was This Post Helpful? 0
  • +
  • -

#24 Xaos  Icon User is offline

  • D.I.C Regular

Reputation: 56
  • View blog
  • Posts: 345
  • Joined: 20-November 13

Posted 26 November 2013 - 03:09 PM

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

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

/**
 *
 * @author User
 */
public class Calculator extends JFrame implements ActionListener{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Calculator c = new Calculator();
        
        JPanel[] row = new JPanel[5];
        JButton[] button = new JButton[19];
        
        String[] buttonString = {"7", "8", "9", "+",
                                 "4", "5", "6", "-",
                                 "1", "2", "3", "*",
                                 ".", "/", "C", "√",
                                 "+/-", "=", "0"};
        int[] dimW = {300, 45, 100, 90};
        int[] dimH = {35, 40};
        
        Dimension displayDimension = new Dimension(dimW[0], dimH[0]);
        Dimension regularDimension = new Dimension(dimW[1], dimH[1]);
        Dimension rColumnDimension = new Dimension(dimW[2], dimH[1]);
        Dimension zeroButDimension = new Dimension(dimW[3], dimH[1]);
        
        boolean[] function = new boolean[4];
        double[] temporary = {0, 0};
        
        JTextArea display = new JTextArea(1,20);
        
        Font font = new Font("Times New Roman", Font.BOLD, 14);
        

    }
    
            Calculator(){
        super("Title");
        setDesign();
        setSize(380, 250);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        GridLayout grid = new GridLayout(5,5);
        setLayout(grid);
        
        for(int i = 0; i < 4; i++)
            function[i] = false;
        
        FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
        FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);
        
        for(int i = 0; i < 5; i++)
        row[i] = new JPanel();
        
        row[0].setLayout(f1);
        
        for(int i = 1; i < 5; i++)
            row[i].setLayout(f2);
        
        for(int i = 0; i < 19; i++){
            button[i] = new JButton();
            button[i].setText(buttonString[i]);
            button[i].setFont(font);
            button[i].addActionListener(this);
        }
        display.setFont(font);
        display.setEditable(false);
        display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        
        display.setPreferredSize(displayDimension);
        
        for(int i = 0;i < 14; i++)
            button[i].setPreferredSize(regularDimension);
        for(int i = 14; i < 18; i++)
            button[i].setPreferredSize(rColumnDimension);
        
        button[18].setPreferredSize(zeroButDimension);
        
        row[0].add(display);
        
        add(row[0]);
        
        for(int i=0; i < 4;i++)
            row[1].add(button[i]);
        row{1].add(button[14]);
        add(row[1]);
        
        for(int i = 4; i< 8; i++)
            row[2].add(button[i]);
        row[2].add(button[15]);
        add(row[2]);
        
        for(int i = 8; i < 12; i++)
            row[3].add(button[i]);
        row[3].add(button[16]);
        add(row[3]);
        
        row[4].add(button[18]);
        for(int i = 12; i < 14; i++)
            row[4].add(button[17]);
        add(row[4]);
        
        setVisible(true);
            }
        
        }
    public final void setDesign(){
        try{
            UIManager.setLookAndFeel(
            "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        }catch(Exception e){
        
        }
    }
    public void actionPerformed(ActionEvent ae){
        
    }
}


This is my code. I'm getting errors : Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: variable function
location: class calculator.Calculator
at calculator.Calculator.<init>(Calculator.java:61)
at calculator.Calculator.main(Calculator.java:23)

(I haven't finished because I was getting this error, didn't want to work more and have to re-start or something). I've looked, but I didn't really see anything wrong.
Was This Post Helpful? 0
  • +
  • -

#25 Xaos  Icon User is offline

  • D.I.C Regular

Reputation: 56
  • View blog
  • Posts: 345
  • Joined: 20-November 13

Posted 26 November 2013 - 03:18 PM

I can't find the 'edit' button, but I fixed the issue. Mods, can merge this post and the one above ^_^ Or just delete the one above
Was This Post Helpful? 0
  • +
  • -

#26 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 136
  • View blog
  • Posts: 338
  • Joined: 22-April 13

Posted 29 November 2013 - 10:53 AM

View PostcodeNtheory, on 26 November 2013 - 05:41 PM, said:

Great tutorial, I am new to java, and was just wondering where you are getting the square root symbol and plus minus symbol for the buttonString array? Thanks again for this tutorial!


I just used an Alt code for the square root symbol(Alt + 251 √) and just a "+""/""-" for the plus minus
Was This Post Helpful? 1
  • +
  • -

#27 AndreeU17  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 137
  • Joined: 29-June 13

Posted 06 January 2014 - 12:47 PM

mod: removed excessive quote of the entire tutorial.

Can someone explain this piece of code to me and how it all connects together?
    public void getResult() {
        double result = 0;
        temporary[1] = Double.parseDouble(display.getText());
        String temp0 = Double.toString(temporary[0]);
        String temp1 = Double.toString(temporary[1]);
        try {
            if(temp0.contains("-")) {
                String[] temp00 = temp0.split("-", 2);
                temporary[0] = (Double.parseDouble(temp00[1]) * -1);
            }
            if(temp1.contains("-")) {
                String[] temp11 = temp1.split("-", 2);
                temporary[1] = (Double.parseDouble(temp11[1]) * -1);
            }
        } catch(ArrayIndexOutOfBoundsException e) {
        }
        try {
            if(function[2] == true)
                result = temporary[0] * temporary[1];
            else if(function[3] == true)
                result = temporary[0] / temporary[1];
            else if(function[0] == true)
                result = temporary[0] + temporary[1];
            else if(function[1] == true)
                result = temporary[0] - temporary[1];
            display.setText(Double.toString(result));
            for(int i = 0; i < 4; i++)
                function[i] = false;
        } catch(NumberFormatException e) {
        }
    }



I don't seem to understand whats the point of temp0, along with the booleans, etc. If anyone can help me clarify this problem whether it be through a PM or simply here, i'd appreciate it!

This post has been edited by modi123_1: 06 January 2014 - 12:52 PM
Reason for edit:: removed excessive quote

Was This Post Helpful? 0
  • +
  • -

#28 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9277
  • View blog
  • Posts: 34,789
  • Joined: 12-June 08

Posted 06 January 2014 - 12:51 PM

Quote

If anyone can help me clarify this problem whether it be through a PM or simply here, i'd appreciate it!

Two things.. One - Please keep the help open to folks and not squirreled away in PMs. Two - there is no need to quote the ENTIRE tutorial. I'll have to remove that.
Was This Post Helpful? 0
  • +
  • -

#29 linklink  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-January 14

Posted 27 January 2014 - 03:40 AM

Learned a lot about GUI and ActionListener with this tutorial so thank you for that. :)/>

I have a question regarding your getResult() Method.

I don't understand the use of the first try clause. I did not include it in my solution and my calculator seems to be working. What is the idea behind this?

I have been trying to improve the code, for instance if I click an operator without anything stored in temporary[0] i get a lot of errors, aswell if I click two operators after eachother or the same operator multiple times without adding numbers or using the getResult() in between.

I thought of something like this example for the addition button:

if (e.getSource() == button[13]) {
			if (!display.getText().equals("")) {
				temporary[0] += Double.parseDouble(display.getText());
				for (int i = 0; i < 4; i++) {
					function[i] = false;
				}
				function[3]  = true;
				display.setText("");
			}
			else {
				function[3] = true;
			}
		}


but when I am testing it, it does not seem to add the display to temporary[0]. For instance if I click 3, +, 3, + 3, =, I get 6.0 and not 9.0. Also I still get errors if i click + multiple times without anything in the display, but I thought my else clause took care of that.

Perhaps a good way would be to make an if-statement checking if anything is stored in temporary[0] when clicking on an operator for the second time, and if so adding to the temporary[0] and displaying the new result. For instance if pressed: 3, +, 3, temporary[0] already contains 3 so, now it will display 6 aswell as adding 6 to temporary[0]. Then whenever a new number is pressed it clears the display but not the temporary and when a new operator is clicked it updates it instead.

Again, nice tutorial, sure learnt a lot, hoping to learn a bit more here.
Thank you, regards link
Was This Post Helpful? 0
  • +
  • -

#30 basi1111  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 02-April 14

Posted 02 April 2014 - 10:28 AM

Thank you.... Nice work... Great explenations....
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3