0

I am writing a program to emulate the windows calculator in java. I have most of the graphics down, but when I add in the text area (the display), it destroys the formatting, and doesn't even put a display in. One interesting thing is that before the text area is put in, most of the buttons only display "..." instead of their actual value. Presumably, this is because the text is too big for the buttons, however, with the display added in, those buttons suddenly get big enough to display the full text on the button and it becomes too wide for the frame.

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

public class Calculator extends JFrame implements ActionListener
{
  public static Scanner in = new Scanner(System.in);

//sets up each JButton
  JButton[] button = new JButton[28];

    JTextArea display = new JTextArea(1,20);

//sets up all the text to put on the buttons
  String[] buttonString = {"MC", "MR", "MS", "M+", "M-",
                                "<-", "CE", "C", "+/-", "squ",
                                "7",  "8",  "9",  "/",  "%",
                                "4",  "5",  "6",  "*", "1/x",
                                "1",  "2",  "3",  "-", "=",
                                "0",        ".",  "+"};

//sets up the boolean values for the different operations
  boolean[] function = {false,false,false,false};
//temporary double values for each number to be for each operation
  double temp1 = 0, temp2 = 0;
//set all font to Times New Roman size 13
  Font font = new Font("Times New Roman", Font.PLAIN, 12);

  public static void main(String[] args)
  {

     //creates calculator
        Calculator calc = new Calculator();
  } 

  public Calculator()
  {
  //makes a calculator with title and size
     super("Calculator");
     setDesign();
     setSize(210,261);
     setResizable(false);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(3,2,2,3);

    int count = 0;
    /*c.gridx = 0;
    c.gridy = 0;
   display.setEditable(false);
   display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
   display.setPreferredSize(new Dimension(190,50));
    c.gridwidth = 5;
    display.setFont(font);
  add(display, c);
    c.gridwidth = 1;*/
    for(int i = 1; i < 5; i++)
    {
        for(int k = 0; k < 5; k++)
        {
            c.gridx = k;
            c.gridy = i;
            button[count] = new JButton(buttonString[count]);
            button[count].addActionListener(this);
            button[count].setPreferredSize(new Dimension(34,27));
            button[count].setFont(font);
            add(button[count++], c);
        }
    }
    for(int i = 0; i < 4; i++)
    {
        c.gridx = i;
        c.gridy = 5;
        button[count] = new JButton(buttonString[count]);
        button[count].addActionListener(this);
        button[count].setPreferredSize(new Dimension(34,27));
        button[count].setFont(font);
        add(button[count++], c);

    }

    c.gridx = 4;
    c.gridy = 5;
    button[count] = new JButton(buttonString[count]);
    button[count].addActionListener(this);
    button[count].setPreferredSize(new Dimension(34,59));
    button[count].setFont(font);
    c.gridheight = 2;
    add(button[count++], c);

    c.gridx = 0;
    c.gridy = 6;
    button[count] = new JButton(buttonString[count]);
    button[count].addActionListener(this);
    button[count].setPreferredSize(new Dimension(73,27));
    button[count].setFont(font);
    c.gridwidth = 2;
    c.gridheight = 1;
    add(button[count++], c);

  c.gridx = 2;
    c.gridy = 6;
    button[count] = new JButton(buttonString[count]);
    button[count].addActionListener(this);
    button[count].setPreferredSize(new Dimension(34,27));
    button[count].setFont(font);
    c.gridwidth = 1;
    add(button[count++], c);

    c.gridx = 3;
    c.gridy = 6;
    button[count] = new JButton(buttonString[count]);
    button[count].addActionListener(this);
    button[count].setPreferredSize(new Dimension(34,27));
    button[count].setFont(font);
    add(button[count++], c);

             setVisible(true);

  }



  public final void setDesign()
  {
     try
     {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

     }
        catch(Exception E){}
  }

  public void actionPerformed(ActionEvent ae)
  {
     if(ae.getSource() == button[10])
        display.append("7");
     if(ae.getSource() == button[11])
        display.append("8");
     if(ae.getSource() == button[12])
        display.append("9");
     if(ae.getSource() == button[15])
        display.append("4");
     if(ae.getSource() == button[16])
        display.append("5");
     if(ae.getSource() == button[17])
        display.append("6");
     if(ae.getSource() == button[20])
        display.append("1");
     if(ae.getSource() == button[21])
        display.append("2");
     if(ae.getSource() == button[22])
        display.append("3");
     if(ae.getSource() == button[7])
        clear();
     if(ae.getSource() == button[8])
        switchSign();
     if(ae.getSource() == button[9])
        sqrt();
     if(ae.getSource() == button[10])
        display.append("7");
     if(ae.getSource() == button[13])
     {
        temp1 = Double.parseDouble(display.getText());
        function[1] = true;
        display.setText("");
     }
     if(ae.getSource() == button[18])
     {
        temp1 = Double.parseDouble(display.getText());
        function[0] = true;
        display.setText("");
     }
     if(ae.getSource() == button[23])
     {
        temp1 = Double.parseDouble(display.getText());
        function[3] = true;
        display.setText("");
     }
     if(ae.getSource() == button[27])
     {
        temp1 = Double.parseDouble(display.getText());
        function[2] = true;
        display.setText("");
     }
     if(ae.getSource() == button[24])
        displayResult();
     if(ae.getSource() == button[25])
        display.append("0");
     if(ae.getSource() == button[6])
        display.setText("");
  }

    public void clear()
    {
        try
        {
            display.setText("0");
            for(int i = 0; i < 4; i++)
                function[i] = false;
            temp1 = 0;
            temp2 = 0;
        }
        catch(NullPointerException e){}
    }

    public void clearEntry()
    {
        try
        {
            display.setText("0");
        }catch(NullPointerException e){}
    }

    public void oneoverx()
    {
        try
        {
            if(display.getText() != "0")
                display.setText("" + Double.parseDouble(display.getText()));
        }
        catch(NumberFormatException e){}
    }
    public void sqrt()
    {
        try
        {
            double value = Math.sqrt(Double.parseDouble(display.getText()));
            display.setText("" + value);
        }
        catch(NumberFormatException e){}
    }

    public void switchSign()
    {
        try
        {
            double value = Double.parseDouble(display.getText());

            if(value != 0)
        {
                value = value * -1;
               display.setText(Double.toString(value));
        }
        else{}
        }
        catch(NumberFormatException e){}
    }

    public void displayResult()
    {
        double result = 0; //variable for result
        temp2 = Double.parseDouble(display.getText()); //second temp number from display
        try
        {
            if(Double.toString(temp1).contains("-"))
            {
                String tempString = Double.toString(temp1);
                String temp = Double.toString(temp1).substring(tempString.indexOf("-"));
                temp1 = Double.parseDouble(temp) * -1;
            }   
            if(Double.toString(temp2).contains("-"))
            {
                String tempString = Double.toString(temp2);
                String temp = Double.toString(temp2).substring(tempString.indexOf("-"));
                temp2 = Double.parseDouble(temp) * -1;
            }   
        }
        catch(ArrayIndexOutOfBoundsException e){}
        try
        {
            if(function[0])
                result = temp1 * temp2;
            else if(function[1])
                result = temp1 / temp2;
            else if(function[2])
                result = temp1 + temp2;
            else if(function[3])
                result = temp1 - temp2;
            display.setText(Double.toString(result));
            for(int i = 0; i < 4; i++)
                function[i] = false;

        }
        catch(NumberFormatException e){}

    }

} 

This is my code, I'm not entirely sure what's wrong with it. Currently, the display is commented out, here is the code for it if you want to find it in the block

c.gridx = 0;
c.gridy = 0;
  display.setEditable(false);
  display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
  display.setPreferredSize(new Dimension(190,50));
    c.gridwidth = 5;
    display.setFont(font);
  add(display, c);
    c.gridwidth = 1;

I'm also not sure if I put all of this in correctly, I've never asked a question on here before. Thanks!

EDIT: This is the calculator I'm trying to emulate but with a more "metal" look and feel. I already have the look and feel so it looks how I want it on my calculator but I want to keep the dimensions accurate. calculator

rdennis42
  • 25
  • 6
  • Never use `setPreferredSize(new Dimension(190,50));` Just leave if for Layout Manager to control the position and size of the components that's why it's made for. – Braj Jun 04 '14 at 21:09
  • @Braj I tried using setSize, and it just made the buttons too big full time. What is wrong with setPreferredSize()? – rdennis42 Jun 04 '14 at 21:10
  • Read it [HERE](http://stackoverflow.com/questions/23974009/painting-on-a-jpanel-inside-a-jscrollpane-doesnt-paint-in-the-right-location?answertab=votes#tab-top) and find the alternative solutions as well. You don't need to set the size at all. – Braj Jun 04 '14 at 21:13

1 Answers1

1

Simply remove all setPreferredSize() and setSize() from your code and call pack() in the end after adding all the components.

What Window#pack() states?

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.

If the window and/or its owner are not displayable yet, both of them are made displayable before calculating the preferred size. The Window is validated after its size is being calculated.

Make one more change:

GridBagConstraints c = new GridBagConstraints();
c.fill=GridBagConstraints.BOTH;                 // ADD THIS LINE

Read more about GridBagConstraints.fill property.

snapshot:

enter image description here

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
  • If I do that, it makes the entire panel bigger, I want to keep it within my set dimensions is there a way to do that? – rdennis42 Jun 04 '14 at 21:21
  • That's why you are getting ellipsis in the buttons because you are setting width lower than minimum preferred width. – Braj Jun 04 '14 at 21:23
  • It is, but ideally I want to make almost an exact clone of the windows vista calculator with the same dimensions. If my problem is the buttons being to small I can take screenshots and use icons on the button instead of the normal numbers, so the ellipses arent too big of a problem. I just want to have the format correct and the text area bigger. Basically, I want to keep the dimensions I had in the setPreferredSize(Dimension). I took out the setPreferredSize() for the display but kept them on the buttons and I like the way that's looking. – rdennis42 Jun 04 '14 at 21:44
  • I put a picture up of sort of what I want it to look like – rdennis42 Jun 04 '14 at 21:56