-1

I try to create this calculator:

I want to add the buttons and the text box using LayoutManager but I don't understand how...

I have another method that gets the string and does the calculation.

Calculator.java

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.LayoutManager;
import java.awt.Container;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.Insets;

import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.JTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.BorderFactory;
import javax.swing.WindowConstants;

public class Calculator extends JFrame
{
    protected JTextField display;

    protected JButton b1 = new JButton("1");
    protected JButton b2 = new JButton("2");
    protected JButton b3 = new JButton("3");
    protected JButton b4 = new JButton("4");
    protected JButton b5 = new JButton("5");
    protected JButton b6 = new JButton("6");
    protected JButton b7 = new JButton("7");
    protected JButton b8 = new JButton("8");
    protected JButton b9 = new JButton("9");
    protected JButton b0 = new JButton("0");

    protected JButton addition = new JButton("+");
    protected JButton subtraction = new JButton("-");
    protected JButton multiplication = new JButton("*");
    protected JButton division = new JButton("/");
    protected JButton result = new JButton("=");
    protected JButton allClear = new JButton("C");
    protected JButton decimalPoint = new JButton(".");

    public Calculator()
    {
        super("Calculator");
        Handler handler = new Handler();

        allClear.addActionListener(handler);
        addition.addActionListener(handler);
        subtraction.addActionListener(handler);
        multiplication.addActionListener(handler);
        division.addActionListener(handler);
        result.addActionListener(handler);
        decimalPoint.addActionListener(handler);

        b0.addActionListener(handler);
        b1.addActionListener(handler);
        b2.addActionListener(handler);
        b3.addActionListener(handler);
        b4.addActionListener(handler);
        b5.addActionListener(handler);
        b6.addActionListener(handler);
        b7.addActionListener(handler);
        b8.addActionListener(handler);
        b9.addActionListener(handler);

        addition.setToolTipText("Addition");
        subtraction.setToolTipText("Subtraction");
        multiplication.setToolTipText("Multiplication");
        division.setToolTipText("Division");
        result.setToolTipText("Result");
        allClear.setToolTipText("All Clear");
        decimalPoint.setToolTipText("Decimal point");

        display = new JTextField(10);
        display.setBorder(BorderFactory.createLineBorder(Color.CYAN));

        // Set a panel's layout manager using the JPanel constructor

        JPanel mainPanel = new JPanel(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.gridy = 0;
        c.gridwidth = 3;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(display, c);

        c = new GridBagConstraints();
        c.gridy = 0;
        c.gridwidth = 1;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(allClear, c);

        c = new GridBagConstraints();
        c.gridy = 1;
        c.gridwidth = 1;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b1, c);

        c = new GridBagConstraints();
        c.gridy = 1;
        c.gridwidth = 1;;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b2, c);

        c = new GridBagConstraints();
        c.gridy = 1;
        c.gridwidth = 1;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b3, c);

        c = new GridBagConstraints();
        c.gridy = 1;
        c.gridwidth = 1;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(division, c);

        c = new GridBagConstraints();
        c.gridy = 2;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b4, c);

        c = new GridBagConstraints();
        c.gridy = 2;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b5, c);

        c = new GridBagConstraints();
        c.gridy = 2;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b6, c);
        add(mainPanel);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();

        c = new GridBagConstraints();
        c.gridy = 2;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(multiplication, c);

        c = new GridBagConstraints();
        c.gridy = 3;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b7, c);

        c = new GridBagConstraints();
        c.gridy = 3;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b8, c);

        c = new GridBagConstraints();
        c.gridy = 3;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b9, c);

        c = new GridBagConstraints();
        c.gridy = 3;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(subtraction, c);

        c = new GridBagConstraints();
        c.gridy = 4;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(b0, c);

        c = new GridBagConstraints();
        c.gridy = 4;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(decimalPoint, c);

        c = new GridBagConstraints();
        c.gridy = 4;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(result, c);

        c = new GridBagConstraints();
        c.gridy = 4;
        c.insets = new Insets(5, 5, 5, 5);
        mainPanel.add(addition, c);

    }

    public Dimension getPreferredSize()
    {
        return new Dimension(250, 300);
    }

    protected class Handler implements ActionListener
    {
        String str;

        public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == b1)
                display.setText(display.getText().concat("1"));

            if (e.getSource() == b2)
                display.setText(display.getText().concat("2"));

            if (e.getSource() == b3)
                display.setText(display.getText().concat("3"));

            if (e.getSource() == b4)
                display.setText(display.getText().concat("4"));

            if (e.getSource() == b5)
                display.setText(display.getText().concat("5"));

            if (e.getSource() == b6)
                display.setText(display.getText().concat("6"));

            if (e.getSource() == b7)
                display.setText(display.getText().concat("7"));

            if (e.getSource() == b8)
                display.setText(display.getText().concat("8"));

            if (e.getSource() == b9)
                display.setText(display.getText().concat("9"));

            if (e.getSource() == b0)
                display.setText(display.getText().concat("0"));

            if (e.getSource() == decimalPoint)
                display.setText(display.getText().concat("."));

            if (e.getSource() == addition)
                display.setText(display.getText().concat("+"));

            if (e.getSource() == subtraction)
                display.setText(display.getText().concat("-"));

            if (e.getSource() == multiplication)
                display.setText(display.getText().concat("*"));

            if (e.getSource() == division)
                display.setText(display.getText().concat("/"));

            if (e.getSource() == allClear)
                display.setText("");

            if (e.getSource() == result)
                str = display.getText();
        }
    }
}

CalculatorTest.java

public class CalculatorTest
{
    public static void main(String[] args)
    {
        java.awt.EventQueue.invokeLater(() -> {
        new Calculator().setVisible(true);
    });
    }
}

I change the code by using GridBagLayout but I don't understand this.

My changes so far: If I delete Dimension getPreferredSize() method and I run,then the calculator shown in minimized size and if I press on Maximize button of the window so I see the full calculator.

If use the method,I get all the calculator but in small size.

I want a bigger buttons and a bigger layout respectively but I don't understand how to do that.

Why the C button has a bigger height than text box height?

Asaf
  • 107
  • 1
  • 12
  • At first, try to move this.setVisible(true); this.pack(); to the end of constructor. – Vitalii Pro Jan 25 '17 at 11:56
  • 2
    1) A `GridBagLayout` would be good for this. 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). I mention this, because a question involving a layout problem does not need tool tips or action listeners included. 3) Don't override the preferred size of a component to return a hard coded value. It is pure guesswork. 4) See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. It uses combinations of layouts rather than a single grid bag layout. – Andrew Thompson Jan 25 '17 at 12:27
  • Here is a [close approximation of that GUI](https://i.stack.imgur.com/xanZS.png). Is it OK, and if not, how would it need to change to fulfil the requirement? – Andrew Thompson Jan 25 '17 at 13:14

1 Answers1

1

A GridBagLayout will be a perfect match for your requirements. Every time you add an object to a container using this layout, you specify a set of constraints that define where you want it to be placed.

In the simple example below you can see that I'm using new Insets(5,5,5,5); to add some spaces between the components, and I make sure that they will fill their whole cell by setting a fill attribute to GridBagConstraints.HORIZONTAL, among other things.

All these constraints are explained very well in this Oracle tutorial, that should tell you how to use this layout manager.

public class JavaDemo extends JFrame {

    public JavaDemo() {
        initComponents();
    }

    private void initComponents() {
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.gridx=0;
        c.gridy=0;
        c.gridwidth=2;
        c.weightx=1;
        c.fill=GridBagConstraints.HORIZONTAL;
        c.insets=new Insets(5,5,5,5);
        mainPanel.add(new JTextField(10), c);

        c = new GridBagConstraints();
        c.gridx=0;
        c.gridy=1;
        c.weightx=1;
        c.fill=GridBagConstraints.HORIZONTAL;
        c.insets=new Insets(5,5,5,5);
        mainPanel.add(new JButton("1"), c);

        c = new GridBagConstraints();
        c.gridx=1;
        c.gridy=1;
        c.weightx=1;
        c.fill=GridBagConstraints.HORIZONTAL;
        c.insets=new Insets(5,5,5,5);
        mainPanel.add(new JButton("2"), c);

        c = new GridBagConstraints();
        c.gridx=0;
        c.gridy=2;
        c.weightx=1;
        c.fill=GridBagConstraints.HORIZONTAL;
        c.insets=new Insets(5,5,5,5);
        mainPanel.add(new JButton("3"), c);

        c = new GridBagConstraints();
        c.gridx=1;
        c.gridy=2;
        c.weightx=1;
        c.fill=GridBagConstraints.HORIZONTAL;
        c.insets=new Insets(5,5,5,5);
        mainPanel.add(new JButton("4"), c);

        add(mainPanel);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        pack();
    }                     

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(() -> {
            new JavaDemo().setVisible(true);
        });
    }           
}

Here's how it looks like.

Example

In a real application you'd want to create the buttons in a loop to avoid the clutter and code duplication. You have to set their listeners and so on. Since it's unrelated to the layout management, I've skipped that for clarity purposes.

Dth
  • 1,916
  • 3
  • 23
  • 34
  • My changes so far: If I delete Dimension getPreferredSize() method and I run,then the calculator shown in minimized size and if I press on Maximize button of the window so I see the full calculator. If use the method,I get all the calculator but in small size. I want a bigger buttons and a bigger layout respectively but I don't understand how to that Why the C button has a bigger height than text box height? – Asaf Jan 29 '17 at 16:01