Hello

I, like everyone else, has made a text based calculator but Ive never worked with GUI in Java. Im using MyEclipse.

Very simple. Numbers, four symbols (+, *, / and -) and "=" Nothing else

How would I even start with this?

Thank you

Yeah, something simple like that.

Also a text box saying input/output

Example, if I push the 2 button in the text box a "2" appears, after if I hit the + button "2+" would appear, after if I hit the 2 button "2+2" would be displayed, and if I hit the "=" button "4" would be displayed in that textbox.

Edited 3 Years Ago by riahc3

What if I hit the "minus" button after first hitting the "two" button and the "plus" button?

Exception and the program breaks.

The point isnt the calculator; Its a simple application for a GUI program.

OK, you have a fair, decent plan. What holds you back to get started?

No idea where to start, what type of project to make, how to make buttons, actions over those buttons, etc....

VS is so much better and MyEclipse is kind of confusing for this.

just ignore the NetBeans wysiwyg "tutorial", the rest should be able to help you out.Java Swing tutorial

Ive followed that tutorial but I cant place the buttons whereever I feel like it so it seems limiting and/or like Im missing something....

Solved. Now when I click a button (buttonone) which has the text "1" on it, I cant add the text to the label

JButton button1 = new JButton("1");
        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                //Here labelinout.text="1"; should work
            }
        });
        button1.setBounds(34, 27, 64, 33);
        panel.add(button1);

Why?

why do you try this: labelinout.text="1";
try labelinout.setText("1");

also, yes, setbounds will work if you work with a null layout, but it'll lead to unwanted results when your user has a different screen resolution.

you might want to read up on layoutmanagers and their influence on the location of your swing components.

why do you try this: labelinout.text="1";
try labelinout.setText("1"); also, yes, setbounds will work if you work with a null layout, but it'll lead to unwanted results when your user has a different screen resolution. you might want to read up on layoutmanagers and their influence on the location of your swing components.

Those do not work. I can only access button1. Cant access any other button and/or that label.

Here it is:

package CalculatorGUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CalulatorGUI extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalulatorGUI frame = new CalulatorGUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CalulatorGUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(null);

        JButton button1 = new JButton("1");
        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {



            }
        });
        button1.setBounds(34, 27, 64, 33);
        panel.add(button1);

        JButton button4 = new JButton("4");
        button4.setBounds(34, 70, 64, 33);
        panel.add(button4);

        JButton button7 = new JButton("7");
        button7.setBounds(34, 114, 64, 33);
        panel.add(button7);

        JButton button2 = new JButton("2");
        button2.setBounds(108, 27, 64, 33);
        panel.add(button2);

        JButton button5 = new JButton("5");
        button5.setBounds(108, 70, 64, 33);
        panel.add(button5);

        JButton button8 = new JButton("8");
        button8.setBounds(108, 114, 64, 33);
        panel.add(button8);

        JButton button3 = new JButton("3");
        button3.setBounds(182, 27, 64, 33);
        panel.add(button3);

        JButton button6 = new JButton("6");
        button6.setBounds(182, 70, 64, 33);
        panel.add(button6);

        JButton button9 = new JButton("9");
        button9.setBounds(182, 114, 64, 33);
        panel.add(button9);

        JButton button0 = new JButton("0");
        button0.setBounds(108, 158, 64, 33);
        panel.add(button0);

        JButton buttonplus = new JButton("+");
        buttonplus.setBounds(34, 203, 64, 33);
        panel.add(buttonplus);

        JButton buttonminus = new JButton("-");
        buttonminus.setBounds(108, 202, 64, 33);
        panel.add(buttonminus);

        JButton buttontimes = new JButton("*");
        buttontimes.setBounds(182, 203, 64, 33);
        panel.add(buttontimes);

        JButton buttondivide = new JButton("/");
        buttondivide.setBounds(258, 203, 64, 33);
        panel.add(buttondivide);

        JLabel labelinout = new JLabel("");
        labelinout.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
            }
        });
        labelinout.setBounds(258, 73, 152, 26);
        panel.add(labelinout);

        JButton buttonequal = new JButton("=");
        buttonequal.setBounds(313, 27, 64, 33);
        panel.add(buttonequal);
    }
}

why don't you declare those labels and such as instance members? keep the declaration of your variables apart will make your code easier to read, and easier to work with.

why don't you declare those labels and such as instance members? keep the declaration of your variables apart will make your code easier to read, and easier to work with.

And do this how.............?

currently, you create them as local variables within your constructor. declare them in your instance, instead of in your constructor.

Done as well. Now instead of clicking on the button, I want to press a (valid) number on my keyborad and it should do that same thing....

package CalculatorGUI;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class CalulatorGUI extends JFrame implements KeyListener {



    private JPanel contentPane;

    JPanel panel = new JPanel();


    JButton button1 = new JButton("1");


    JButton button4 = new JButton("4");


    JButton button7 = new JButton("7");


    JButton button2 = new JButton("2");


    JButton button5 = new JButton("5");


    JButton button8 = new JButton("8");


    JButton button3 = new JButton("3");


    JButton button6 = new JButton("6");


    JButton button9 = new JButton("9");


    JButton button0 = new JButton("0");


    JButton buttonplus = new JButton("+");


    JButton buttonminus = new JButton("-");


    JButton buttontimes = new JButton("*");


    JButton buttondivide = new JButton("/");


    JLabel labelinout = new JLabel("");


    JButton buttonequal = new JButton("=");
    private final JButton buttonclear = new JButton("CLEAR");
    private final JButton buttondot = new JButton(".");
    private final JButton buttonopen = new JButton("(");
    private final JButton buttonclose = new JButton(")");





    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InstantiationException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (UnsupportedLookAndFeelException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalulatorGUI frame = new CalulatorGUI();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CalulatorGUI()  {
        setTitle("Calculator");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 341);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        panel.setLayout(null);
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button1.getText());

            }
        });


        button1.setBounds(34, 27, 64, 33);
        panel.add(button1);
        button4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button4.getText());
            }
        });


        button4.setBounds(34, 70, 64, 33);
        panel.add(button4);
        button7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button7.getText());
            }
        });


        button7.setBounds(34, 114, 64, 33);
        panel.add(button7);
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button2.getText());
            }
        });


        button2.setBounds(108, 27, 64, 33);
        panel.add(button2);
        button5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button5.getText());
            }
        });


        button5.setBounds(108, 70, 64, 33);
        panel.add(button5);
        button8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button8.getText());
            }
        });


        button8.setBounds(108, 114, 64, 33);
        panel.add(button8);
        button3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button3.getText());
            }
        });


        button3.setBounds(182, 27, 64, 33);
        panel.add(button3);
        button6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button6.getText());
            }
        });


        button6.setBounds(182, 70, 64, 33);
        panel.add(button6);
        button9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button9.getText());
            }
        });


        button9.setBounds(182, 114, 64, 33);
        panel.add(button9);
        button0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+button0.getText());
            }
        });


        button0.setBounds(108, 158, 64, 33);
        panel.add(button0);
        buttonplus.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttonplus.getText());
            }
        });


        buttonplus.setBounds(34, 203, 64, 33);
        panel.add(buttonplus);
        buttonminus.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttonminus.getText());
            }
        });


        buttonminus.setBounds(108, 202, 64, 33);
        panel.add(buttonminus);
        buttontimes.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttontimes.getText());
            }
        });


        buttontimes.setBounds(182, 203, 64, 33);
        panel.add(buttontimes);
        buttondivide.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttondivide.getText());
            }
        });


        buttondivide.setBounds(258, 203, 64, 33);
        panel.add(buttondivide);


        labelinout.setBounds(258, 73, 152, 26);
        panel.add(labelinout);
        buttonequal.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ScriptEngineManager mgr = new ScriptEngineManager();
                ScriptEngine engine = mgr.getEngineByName("JavaScript");
                String formula = labelinout.getText();
                Double resultado;
                try {
                    resultado =  (Double) engine.eval(formula);
                    labelinout.setText(String.valueOf(resultado));
                    JOptionPane.showMessageDialog(null, String.valueOf(resultado), "InfoBox", JOptionPane.INFORMATION_MESSAGE);

                } catch (ScriptException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }


            }
        });


        buttonequal.setBounds(313, 27, 64, 33);
        panel.add(buttonequal);
        buttonclear.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText("");
            }
        });
        buttonclear.setBounds(342, 203, 68, 33);

        panel.add(buttonclear);
        buttondot.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttondot.getText());
            }
        });
        buttondot.setBounds(182, 158, 64, 33);

        panel.add(buttondot);
        buttonopen.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttonopen.getText());
            }
        });
        buttonopen.setBounds(34, 247, 64, 33);

        panel.add(buttonopen);
        buttonclose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                labelinout.setText(labelinout.getText()+buttonclose.getText());
            }
        });
        buttonclose.setBounds(108, 246, 64, 33);

        panel.add(buttonclose);
    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyPressed(KeyEvent e) {


    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }
}

With this, I should be able to get into more advanced GUI applications....

Before you get carried away with more advanced apps, there's a lot more you can learn from this one. eg

  • use a proper layout manager (eg GridLayout) rather than the un-portable null layout
  • replace all those repeated variables and repeated blocks of code with an array of JButtons and a loop
  • use Actions to define and handle the responses to the buttons and the keyboard (via Key Bindings) consistently

So how do I do the keypresses that call the action that is the click on those buttons?

Pressing 3 on my keyboard launches the event of pressing the "3" button.

The anonymous inner class is good stuff. While you are learning you could explore the
Building the abstract action listener class by writing the class that implements ActionListener. As your components increase you can maintain them in separate small classes.

Click Here

This article has been dead for over six months. Start a new discussion instead.