I've had enough. I just don't get what's wrong at all.
I coded a basic calculator program, and it compiled correctly, no exceptions thingy, sooo... it's probably my mistake --- nothing appears on the calculator's GUI. It's a blank window with just the title. And when executing programs like this, shouldn't something be happening in the command prompt before the program pops out (well, that's what happened in my previous not-so-good-yet-working-calculator)?

*** Note: I am actually very embarassed to even post this thing since I haven't checked on anything yet, like if the program does what it's supposed to >////<. Ugh.

Here it goes:

//Revised Calculator (I had previously made one but not-so-efficient)
//Made by Some Inexperience Wanna-Be Programmer
//My apologies, really.

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

public class MyCalculator extends JFrame
{
    private JLabel inputL, resultL;
    private JTextField inputTF, resultTF;
    private JButton buttons [] = new JButton[17];
    private JPanel mainPane, editablePane, bottomPane;

    //Handler for all buttons
    private Handler bHandler;

    private static final int WIDTH = 250;
    private static final int HEIGHT = 350;

    int i=0; // just a counter since I ought to use loops later

    public MyCalculator()
    {
        //Create panels
        mainPane = new JPanel();
        editablePane = new JPanel();
        bottomPane = new JPanel();

        //Create the two labels
        inputL = new JLabel ("Input : ", SwingConstants.RIGHT);
        resultL = new JLabel ("Result: ", SwingConstants.RIGHT);

        //Create two textfields
        inputTF = new JTextField(10);
        inputTF.setEditable(false);
        resultTF = new JTextField(10);
        resultTF.setEditable(false);
        resultTF.setText("0.0");
        inputTF.setText("0.0");

        //Register event handlers
        bHandler = new Handler();

        //Create number buttons
        for (int i = 0; i <=9; i++)
        {
            buttons[i] = new JButton (Integer.toString(i));
            buttons[i].addActionListener(bHandler);
        }

        //Create functional buttons
        buttons[10] = new JButton("."); // decimal button
        buttons[11] = new JButton("+"); // addition button
        buttons[12] = new JButton("-"); // subtraction button
        buttons[13] = new JButton("*"); // multiplication button
        buttons[14] = new JButton("/"); // division button
        buttons[15] = new JButton("="); // equals button
        buttons[16] = new JButton("C"); // clear button

        //Set title of the window
        setTitle("Simple Calculator");

        //Made many JPanels, thinking I'll insert a panel in the "parent" panel, hopefully to get a more organized look
        //There could really be something wrong here x______x
        mainPane.setLayout(new GridLayout(2,1));
        editablePane.setLayout(new GridLayout(2,2));
        editablePane.add(inputL);
        editablePane.add(inputTF);
        editablePane.add(resultL);
        editablePane.add(resultTF);
        mainPane.add(editablePane);
        bottomPane.setLayout(new GridLayout(1,2));
        editablePane.setLayout(new GridLayout(4,3));
        for (i=7; i<10; i++)
            editablePane.add(buttons[i]);
        for (i=4; i<7; i++)
            editablePane.add(buttons[i]);
        for (i=1; i<4; i++)
            editablePane.add(buttons[i]);
        editablePane.add(buttons[0]);
        editablePane.add(buttons[10]);
        bottomPane.add(editablePane);
        editablePane.setLayout(new GridLayout(4,2));
        for (i=11; i<17; i++)
            editablePane.add(buttons[i]);
        bottomPane.add(editablePane);
        mainPane.add(bottomPane);

        //Set the size of the window and display it
        setSize(WIDTH,HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public class Handler implements ActionListener
    {
        double result = 0.0;
        String displayedNum = "0.0";
        double storedNum1 = 0.0;
        double storedNum2 = 0.0;
        String operation = null;
        boolean contOperation = false;

        public void assign (String number)
        {
            //this one here basically replaces the original text (which is 0.0) with the entered number
            // in the input text field when the first number clicked on.
            if ((inputTF.getText()).equals("0.0"))
                inputTF.setText(number);
            else
            {
                //this allows the concatenation of numbers when pressed
                displayedNum = inputTF.getText();
                inputTF.setText(displayedNum + number);
            }
        }

        //I'm still unsure of this method, you know how I can't check the program since nothing comes out?
        //I plan to use this method to check for, obviously, if the user has finished an equation and
        //would still want to continue
        //i.e. 8+8=16... is entered by a user and he/she presses the subtract button and enters the number 9
        //16 would then be stored as the first number and 9 as the second number: 16-9
        public void checkContinuousOperation (boolean continuedOperation)
        {
            if (continuedOperation == false)
            {
                storedNum1 = Double.parseDouble(inputTF.getText());
                displayedNum = "";
                inputTF.setText(""+displayedNum);
            }
            else
            {
                storedNum1 = Double.parseDouble(resultTF.getText());
                displayedNum = "";
                inputTF.setText(""+displayedNum);
            }
        }

        public void actionPerformed(ActionEvent e)
        {
            Object source = e.getSource();  //gets the source of the event
            // this ladderized if-else if checks which of the buttons is clicked
            // the assign method basically handles concatenating the numbers together and displays 'em
            for (i=0; i<10; i++)
            {
                if (source == buttons[i])
                    assign(Integer.toString(i));
            }

            if (source == buttons[10])
                assign(".");

            else if (source == buttons[11])
            {
                checkContinuousOperation(true);
                operation = "add";
            }
            else if (source == buttons[12])
            {
                checkContinuousOperation(true);
                operation = "sub";
            }
            else if (source == buttons[13])
            {
                checkContinuousOperation(true);
                operation = "mult";
            }
            else if (source == buttons[14])
            {
                checkContinuousOperation(true);
                operation = "div";
            }

            //checks if the "=" button is pressed
            //performs calculations and prints result
            //after showing the result, second number is to be reset-ed to 0
            //BTW, I hadn't really placed what it's supposed to do if the equal button is pressed first
            else if (source == buttons[15])
            {
                storedNum2 = Double.parseDouble(inputTF.getText());

                if (operation == "add") 
                {
                    result = storedNum1 + storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
                else if (operation == "sub") 
                {
                    result = storedNum1 - storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
                else if (operation ==  "mult") 
                {
                    result = storedNum1 * storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
                else if (operation == "div") 
                {
                    result = storedNum1 / storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
            }

            //Clear button
            else if (source == buttons[16])
            {
                storedNum1 = 0;
                storedNum2 = 0;
                resultTF.setText("0.0");
                inputTF.setText("0.0");
                contOperation = false;
            }
        }
    }

public static void main(String [] args)
{
    MyCalculator calculatorObject = new MyCalculator();
}
}

I know it's still a lil' messed up but what matters to me right now is that I get it to appear... 200+ lines of code for a blank window makes me feel reaaaaally upset. Nope, it's not homework. I previously did this (that was my homework but that calculator has a messy interface and would not work with changing continuous operations... like if you press 8+7-3... it will result in random numbers, though with continuous same operations it would work fine). That one ran. I think their main difference is with the new method, checkContinuousOperation, added and oh... I used Container for that one, not JPanel, which I'm not familiar with at all yet. I'm still weak with Java, beginner level. And if there's anything else I need to work on, please do tell. Thank you!

Recommended Answers

All 9 Replies

well, as far as I can see, you never linked the 'editablePane' to which you add all your components, to the actual JFrame.
my guess, it's something like that you've forgotten.

True. Didn't know that (stupid me). Thank you.
Thanks. Now that I get to see my work... I find it amazingly ridiculous. It doesn't do or look like what it's supposed to.

Assuming I've got this code now... nevermind the ugly appearance, imma work on it later:

//Revised Calculator (I had previously made one yet not-so-efficient yet)
//Made by Some Inexperience Wanna-Be Programmer
//My apologies, really.

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

public class MyCalculator extends JFrame
{
    private JLabel inputL, resultL;
    private JTextField inputTF, resultTF;
    private JButton buttons [] = new JButton[17];
    private JPanel mainPane, editablePane, bottomPane;

    //Handler for all buttons
    private Handler bHandler;

    private static final int WIDTH = 250;
    private static final int HEIGHT = 350;

    int i=0; // just a counter since I ought to use loops 

    public MyCalculator()
    {
        //Create panels
        mainPane = new JPanel();
        editablePane = new JPanel();
        bottomPane = new JPanel();

        //Create the two labels
        inputL = new JLabel ("Input : ", SwingConstants.RIGHT);
        resultL = new JLabel ("Result: ", SwingConstants.RIGHT);

        //Create two textfields
        inputTF = new JTextField(10);
        inputTF.setEditable(false);
        resultTF = new JTextField(10);
        resultTF.setEditable(false);
        resultTF.setText("0.0");
        inputTF.setText("0.0");

        //Register event handlers
        bHandler = new Handler();

        //Create number buttons
        for (int i = 0; i <=9; i++)
        {
            buttons[i] = new JButton (Integer.toString(i));
            buttons[i].addActionListener(bHandler);
        }

        //Create functional buttons
        buttons[10] = new JButton(".");
        buttons[11] = new JButton("+");
        buttons[12] = new JButton("-");
        buttons[13] = new JButton("*");
        buttons[14] = new JButton("/");
        buttons[15] = new JButton("=");
        buttons[16] = new JButton("C");

        //Set title of the window
        setTitle("Simple Calculator by AVG");

        //Made many JPanels, thinking I'll insert a panel in the "parent" panel, hopefully to get a more organized look
        mainPane.setLayout(new GridLayout(2,1));
        editablePane.setLayout(new GridLayout(2,2));
        editablePane.add(inputL);
        editablePane.add(inputTF);
        editablePane.add(resultL);
        editablePane.add(resultTF);
        mainPane.add(editablePane);
        bottomPane.setLayout(new GridLayout(1,2));
        editablePane.setLayout(new GridLayout(4,3));
        for (i=7; i<10; i++)
            editablePane.add(buttons[i]);
        for (i=4; i<7; i++)
            editablePane.add(buttons[i]);
        for (i=1; i<4; i++)
            editablePane.add(buttons[i]);
        editablePane.add(buttons[0]);
        editablePane.add(buttons[10]);
        bottomPane.add(editablePane);
        editablePane.setLayout(new GridLayout(4,2));
        for (i=11; i<17; i++)
            editablePane.add(buttons[i]);
        bottomPane.add(editablePane);
        mainPane.add(bottomPane);
        setContentPane(mainPane);

        //Set the size of the window and display it
        setSize(WIDTH,HEIGHT);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public class Handler implements ActionListener
    {
        double result = 0.0;
        String displayedNum = "0.0";
        double storedNum1 = 0.0;
        double storedNum2 = 0.0;
        String operation = null;
        boolean contOperation = false;

        public void assign (String number)
        {
            //this one here basically replaces the original text (which is 0.0) with the entered number
            // in the input text field when the first number clicked on.
            if ((inputTF.getText()).equals("0.0"))
                inputTF.setText(number);
            else
            {
                //this allows the concatenation of numbers when pressed
                displayedNum = inputTF.getText();
                inputTF.setText(displayedNum + number);
            }
        }

        //I'm still unsure of this method, you know how I can't check the program since nothing comes out?
        //I plan to use this method to check for, obviously, if the user has finished an equation and
        //would still want to continue
        //i.e. 8+8=16... is entered by a user and he/she presses the subtract button and enters the number 9
        //16 would then be stored as the first number and 9 as the second
        public void checkContinuousOperation (boolean continuedOperation)
        {
            if (continuedOperation == false)
            {
                storedNum1 = Double.parseDouble(inputTF.getText());
                displayedNum = "";
                inputTF.setText(""+displayedNum);
            }
            else
            {
                storedNum1 = Double.parseDouble(resultTF.getText());
                displayedNum = "";
                inputTF.setText(""+displayedNum);
            }
        }

        public void actionPerformed(ActionEvent e)
        {
            Object source = e.getSource();  //gets the source of the event
            // this ladderized if-else if checks which of the buttons is clicked
            // the assign method basically handles concatinating the numbers together and displays 'em

            for (i=0; i<10; i++)
            {
                if (source == buttons[i])
                    assign(Integer.toString(i));
            }

            if (source == buttons[10])
                assign(".");

            else if (source == buttons[11])
            {
                checkContinuousOperation(contOperation);
                operation = "add";
            }
            else if (source == buttons[12])
            {
                checkContinuousOperation(contOperation);
                operation = "sub";
            }
            else if (source == buttons[13])
            {
                checkContinuousOperation(contOperation);
                operation = "mult";
            }
            else if (source == buttons[14])
            {
                checkContinuousOperation(contOperation);
                operation = "div";
            }

            //checks if the "=" button is pressed
            //performs calculations and prints result
            //after showing the result, second number is to be reset-ed to 0
            else if (source == buttons[15])
            {
                storedNum2 = Double.parseDouble(inputTF.getText());
                contOperation = true;

                if (operation == "add") 
                {
                    result = storedNum1 + storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
                else if (operation == "sub") 
                {
                    result = storedNum1 - storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
                else if (operation ==  "mult") 
                {
                    result = storedNum1 * storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
                else if (operation == "div") 
                {
                    result = storedNum1 / storedNum2;
                    resultTF.setText("" + result);
                    storedNum2 = 0;
                }
            }

            //Clear button
            else if (source == buttons[16])
            {
                storedNum1 = 0;
                storedNum2 = 0;
                resultTF.setText("0.0");
                inputTF.setText("0.0");
                contOperation = false;
            }
        }
    }

public static void main(String [] args)
{
    MyCalculator calculatorObject = new MyCalculator();
}
}

Why is it that when I click on a button, nothing happens (except for the number buttons)?
buttons[10] up to buttons[16] aren't working at all.
I don't think there's anything wrong with if (source == buttons[10]) or the line of code under it, yet, clicking on the decimal button doesn't make anything happen :((

BTW, since this question is related to the code above, I decided to just continue the discussion here or should I need to make a new thread?

can you give a for instance of a button and what you expect it to do?

but this, for instance:

if(operation == "sub")

is wrong, that's supposed to be

if(operation.equals("sub"))

or, if you wish to be extra sure to avoid nullpointerexceptions:

if ("sub".equals(operation))

Thanks for the tip about that one, changed the code for efficiency. But what I was referring to was...
I could use the number buttons fine but the addition,subtraction,multiplication,division,clear & decimal buttons don't work. There just seems to be no reason why it wouldn't.

Let's say for example buttons[10] // the decimal button
It should be adding a "." to the number(s) (well, it's a string of numbers) on the input textfield.
Well, of course it gets the number on screen first then sets the input textfield to the number it got and concatenates it with "." as with the statements in code lines 115-116 state.

BUT IT DOESN'T WORK when I used the same method for number buttons, yet those number buttons worked fine.

If you want your "functional" buttons to do something you should add an action listener to them ;)

that's because for the JButtons with the numbers (0 through 9) you've added the actionListeners, you haven't added it to the other JButtons.

your application can only be as smart as you make it. if you don't tell your code that an action must be executed when a JButton is clicked, it won't be executed.

Snap!

commented: snap indeed :) was typing that while eating, took me a while ;) +14

LOL. I'm a forgetful person, aren't I?
Thanks, JamesCherrill.
Thank you for the tip as well, stultuske.

Thaaaaank you, really. Now, all I'll have to worry about is the appearance :))

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.