4 Replies - 248 Views - Last Post: 02 May 2013 - 03:28 PM Rate Topic: -----

#1 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

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

Key Release

Posted 01 May 2013 - 10:45 PM

The past few hours i've been designing a GUI calculator to build up on my beginner/novice Java skills.

I'm having trouble with something on the KeyRelease I presume. When I go in to press the "-" key on my Number Pad, it will automatically remove itself. but when I do it with the "-" on the keyboard itself it works. I don't know if it's a seperate variable I need to be using but any help would be appreciated. Also I want it so if there isn't a value already in the text area to put the dash there. if there is a value already in the text area to turn my subtraction boolean on.

Here's the code:

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

public class Calculator extends JFrame implements ActionListener, KeyListener {
    
    double temp;
    double solveTemp;
    
    Boolean addBool = false;
    Boolean subBool = false;
    Boolean divBool = false;
    Boolean mulBool = false;
    
    Font font = new Font("Times New Roman",Font.BOLD,14);
    Dimension btn = new Dimension(45,40);
    Dimension cebtn = new Dimension(100,40);
    Dimension btn1 = new Dimension(90,40);
    Dimension box = new Dimension(300,35);
    
    JPanel row1 = new JPanel();
    JTextField display = new JTextField(20);
    
    JPanel row2 = new JPanel();
    JButton seven = new JButton("7");
    JButton eight = new JButton("8");
    JButton nine = new JButton("9");
    JButton add = new JButton("+");
    JButton ce = new JButton("C");
    
    JPanel row3 = new JPanel();
    JButton four = new JButton("4");
    JButton five = new JButton("5");
    JButton six = new JButton("6");
    JButton subtract = new JButton("-");
    JButton sqrt = new JButton("√");
    
    JPanel row4 = new JPanel();
    JButton one = new JButton("1");
    JButton two = new JButton("2");
    JButton three = new JButton("3");
    JButton multiply = new JButton("*");
    JButton plusmin = new JButton("+/-");
    
    JPanel row5 = new JPanel();
    JButton zero = new JButton("0");
    JButton decimal = new JButton(".");
    JButton divide = new JButton("/");
    JButton equals = new JButton("=");
    
    Calculator() {
        super("Calculator");
        setDesign();
        setSize(380,250);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        GridLayout form = new GridLayout(5,5,1,1);
        setLayout(form);
        
        FlowLayout r1 = new FlowLayout(FlowLayout.CENTER);
        row1.setLayout(r1);
        row1.add(display);
        display.setHorizontalAlignment(JTextField.CENTER);
        display.setFont(font);
        display.setPreferredSize(box);
        display.addKeyListener(this);
        add(row1);
        
        FlowLayout flow = new FlowLayout(FlowLayout.CENTER,1,1);
        
        row2.setLayout(flow);
        row2.setBackground(Color.GRAY);
        row2.add(seven);
        row2.add(eight);
        row2.add(nine);
        row2.add(add);
        row2.add(ce);
        seven.setFont(font);
        eight.setFont(font);
        nine.setFont(font);
        add.setFont(font);
        ce.setFont(font);
        seven.setForeground(Color.lightGray);
        eight.setForeground(Color.lightGray);
        nine.setForeground(Color.lightGray);
        seven.setBackground(Color.DARK_GRAY);
        eight.setBackground(Color.DARK_GRAY);
        nine.setBackground(Color.DARK_GRAY);
        add.setBackground(Color.DARK_GRAY);
        add.setForeground(Color.cyan);
        ce.setBackground(Color.DARK_GRAY);
        ce.setForeground(Color.white);
        seven.setPreferredSize(btn);
        eight.setPreferredSize(btn);
        nine.setPreferredSize(btn);
        add.setPreferredSize(btn);
        ce.setPreferredSize(cebtn);
        seven.addActionListener(this);
        eight.addActionListener(this);
        nine.addActionListener(this);
        add.addActionListener(this);
        ce.addActionListener(this);
        add(row2);
        
        row3.setLayout(flow);
        row3.setBackground(Color.lightGray);
        row3.add(four);
        row3.add(five);
        row3.add(six);
        row3.add(subtract);
        row3.add(sqrt);
        four.setFont(font);
        five.setFont(font);
        six.setFont(font);
        subtract.setFont(font);
        sqrt.setFont(font);
        four.setForeground(Color.lightGray);
        five.setForeground(Color.lightGray);
        six.setForeground(Color.lightGray);
        four.setBackground(Color.gray);
        five.setBackground(Color.gray);
        six.setBackground(Color.gray);
        subtract.setForeground(Color.cyan);
        subtract.setBackground(Color.gray);
        sqrt.setForeground(Color.yellow);
        sqrt.setBackground(Color.gray);
        four.setPreferredSize(btn);
        five.setPreferredSize(btn);
        six.setPreferredSize(btn);
        subtract.setPreferredSize(btn);
        sqrt.setPreferredSize(cebtn);
        four.addActionListener(this);
        five.addActionListener(this);
        six.addActionListener(this);
        subtract.addActionListener(this);
        sqrt.addActionListener(this);
        add(row3);
        
        row4.setLayout(flow);
        row4.setBackground(Color.GRAY);
        row4.add(one);
        row4.add(two);
        row4.add(three);
        row4.add(multiply);
        row4.add(plusmin);
        one.setForeground(Color.lightGray);
        two.setForeground(Color.lightGray);
        three.setForeground(Color.lightGray);
        one.setBackground(Color.darkGray);
        two.setBackground(Color.darkGray);
        three.setBackground(Color.darkGray);
        multiply.setForeground(Color.cyan);
        multiply.setBackground(Color.darkGray);
        plusmin.setForeground(Color.yellow);
        plusmin.setBackground(Color.darkGray);
        one.setFont(font);
        two.setFont(font);
        three.setFont(font);
        multiply.setFont(font);
        plusmin.setFont(font);
        one.setPreferredSize(btn);
        two.setPreferredSize(btn);
        three.setPreferredSize(btn);
        multiply.setPreferredSize(btn);
        plusmin.setPreferredSize(cebtn);
        one.addActionListener(this);
        two.addActionListener(this);
        three.addActionListener(this);
        multiply.addActionListener(this);
        plusmin.addActionListener(this);
        add(row4);
        
        row5.setLayout(flow);
        row5.setBackground(Color.lightGray);
        row5.add(zero);
        row5.add(decimal);
        row5.add(divide);
        row5.add(equals);
        zero.setFont(font);
        decimal.setFont(font);
        divide.setFont(font);
        equals.setFont(font);
        zero.setBackground(Color.gray);
        decimal.setBackground(Color.gray);
        divide.setBackground(Color.gray);
        equals.setBackground(Color.gray);
        decimal.setForeground(Color.yellow);
        divide.setForeground(Color.cyan);
        zero.setForeground(Color.lightGray);
        equals.setForeground(Color.white);
        zero.setPreferredSize(btn1);
        decimal.setPreferredSize(btn);
        divide.setPreferredSize(btn);
        equals.setPreferredSize(cebtn);
        zero.addActionListener(this);
        decimal.addActionListener(this);
        divide.addActionListener(this);
        equals.addActionListener(this);
        add(row5);
        
        setVisible(true);
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        //e.getSource();
        if(e.getSource() == seven) {
            addingText("7");
        }
        if(e.getSource() == eight) {
            addingText("8");
        }
        if(e.getSource() == nine) {
            addingText("9");
        }
        if(e.getSource() == add) {
            temp = Double.parseDouble(display.getText());
            addBool = true;
            display.setText("");
        }
        if(e.getSource() == ce) {
            clear();
        }
        if(e.getSource() == four) {
            addingText("4");
        }
        if(e.getSource() == five) {
            addingText("5");
        }
        if(e.getSource() == six) {
            addingText("6");
        }
        if(e.getSource() == subtract) {
            temp = Double.parseDouble(display.getText());
            subBool = true;
            display.setText("");
        }
        if(e.getSource() == sqrt) {
            getSqrt();
        }
        if(e.getSource() == one) {
            addingText("1");
        }
        if(e.getSource() == two) {
            addingText("2");
        }
        if(e.getSource() == three) {
            addingText("3");
        }
        if(e.getSource() == multiply) {
            temp = Double.parseDouble(display.getText());
            mulBool = true;
            display.setText("");
        }
        if(e.getSource() == plusmin) {
            getPosNeg();
        }
        if(e.getSource() == zero) {
            addingText("0");
        }
        if(e.getSource() == decimal) {
            addingText(".");
        }
        if(e.getSource() == divide) {
            temp = Double.parseDouble(display.getText());
            divBool = true;
            display.setText("");
        }
        if(e.getSource() == equals) {
            getResult();
        }
    }
    
    @Override
    public void keyTyped(KeyEvent txt) {
    }
    
    @Override
    public void keyPressed(KeyEvent txt) {
        int key = txt.getKeyCode();
        try {
            if(key == KeyEvent.VK_ADD) {
                temp = Double.parseDouble(display.getText());
                addBool = true;
                display.setText("");
            }
            if(key == KeyEvent.VK_SUBTRACT) {
                if(display.getText().isEmpty()) {
                    getPosNeg();
                }
                else {
                    temp = Double.parseDouble(display.getText());
                    subBool = true;
                }
            }
            if(key == KeyEvent.VK_DIVIDE) {
                temp = Double.parseDouble(display.getText());
                divBool = true;
            }
            if(key == KeyEvent.VK_MULTIPLY) {
                temp = Double.parseDouble(display.getText());
                mulBool = true;
            }
            if(key == KeyEvent.VK_ENTER) {
                getResult();
            }
            else {
            }
        } catch(NumberFormatException e) {
        }
    }
    
    @Override
    public void keyReleased(KeyEvent txt) {
        int key = txt.getKeyCode();
        try {
            if(key == KeyEvent.VK_ADD) {
                display.setText("");
            }
            if(key == KeyEvent.VK_SUBTRACT) {
                if(display.getText().isEmpty()) {
                    display.setText("-");
                } else {
                    display.setText("");
                }
            }
            if(key == KeyEvent.VK_MULTIPLY) {
                display.setText("");
            }
            if(key == KeyEvent.VK_DIVIDE) {
                display.setText("");
            }
            else {
            }
        } catch (NumberFormatException e) {
        }
    }
    
    public void getResult() {
        double solveTemp1;
        double temp1;
        double solveTemp2 = 0;
        solveTemp = Double.parseDouble(display.getText());
        String tempString = Double.toString(temp);
        String solveTempString = Double.toString(solveTemp);
        try {
            if(tempString.contains("-")) {
                String[] tString = tempString.split("-", 2);
                temp1 = Double.parseDouble(tString[1]);
                temp = (temp1 * -1);
            }
            if(solveTempString.contains("-")) {
                String[] stString = solveTempString.split("-", 2);
                solveTemp1 = Double.parseDouble(stString[1]);
                solveTemp = (solveTemp1 * -1);        
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            
        }
        try {
            if(mulBool == true) {
                solveTemp2 = temp * solveTemp;
            } else if(divBool == true) {
                solveTemp2 = temp / solveTemp;
            } else if(addBool == true) {
                solveTemp2 = temp + solveTemp;
            } else if(subBool == true) {
                solveTemp2 = temp - solveTemp;
            }
            display.setText(Double.toString(solveTemp2));
            addBool = false;
            subBool = false;
            mulBool = false;
            divBool = false;
        } catch (NumberFormatException nfe) {
        }
    }
    
    public void addingText(String txtAdd) {
        String currentTxt = display.getText();
        if(currentTxt == null) {
            display.setText(txtAdd);
        } else {
            display.setText(currentTxt + txtAdd);
        }
    }
    
    public void getSqrt() {
        try {
            double value = Double.parseDouble(display.getText());
            double value1 = Math.sqrt(value);
            String newTxt = Double.toString(value1);
            display.setText(newTxt);
        } catch (NumberFormatException nfe) {
        }
    }
    
    public void getPosNeg() {
        try {
            double value = Double.parseDouble(display.getText());
            if (value > 0) {
                double value1 = value * (-1);
                String newTxt = Double.toString(value1);
                display.setText(newTxt);
            }
            if (value < 0) {
                double value1 = value * (-1);
                String newTxt = Double.toString(value1);
                display.setText(newTxt);
            } else {
            }
        } catch (NumberFormatException nfe) {
        }
    }
    
    public void clear() {
        display.setText(null);
        display.setEditable(true);
        addBool = false;
        subBool = false;
        mulBool = false;
        divBool = false;
        temp = 0;
        solveTemp = 0;
    }
    
    public final void setDesign() {
        try {
            UIManager.setLookAndFeel(
                    "com.sun.java.swing.plaf.metal.MetalLookAndFeel");
        } catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
        }
    }
    
    public static void main(String[] arguments) {
        Calculator calculator = new Calculator();
    }
    
}



Is This A Good Question/Topic? 0
  • +

Replies To: Key Release

#2 Gungnir  Icon User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Key Release

Posted 02 May 2013 - 12:53 AM

In java.awt.event.KeyEvent, there is no unique key code for the standard subtraction key, so you have to substitute it in yourself. There are two ways to differentiate between these two keys:
  • Check the location
  • Check the key code


1.
//I haven't tested this, but it's possible that both keys will return
//KEY_LOCATION_NUMPAD, due to how they're dealt with in the Java KeyEvent class
keyLocation = txt.getKeyLocation
if(keyLocation == KEY_LOCATION_NUMPAD)
{
    if(key == KeyEvent.VK_SUBTRACT)
    {
        //your code here
    }
}



2.
    if(key == 109) //numpad '-' <- Not A Face
    {
        //your code here
    }
    if(key == 173) //regular '-'
    {
        //your code here
    }



Further Reading:
- W3 > Keyboard Events and Codes

This post has been edited by Gungnir: 02 May 2013 - 01:12 AM

Was This Post Helpful? 2
  • +
  • -

#3 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 838
  • View blog
  • Posts: 2,574
  • Joined: 29-July 11

Re: Key Release

Posted 02 May 2013 - 08:43 AM

Keeping track of key codes like that is unnecessarily complicated. A character will be the same, regardless of its location.

public void keyPressed(KeyEvent e) {
		char c = e.getKeyChar();
		System.out.println(c);
		if(c == '-') {
			System.out.println("- pressed");
		}
	}

Was This Post Helpful? 1
  • +
  • -

#4 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

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

Re: Key Release

Posted 02 May 2013 - 02:29 PM

Thank you guys for the help. I fixed the problem with the whole numpad subtraction key not working with the negative numbers with your help but now i'm struggling on the part with after I call my subtraction boolean with keypressed I run into an issue with the negative or subtraction sign still showing up on the display.

Like if I do -5 MINUS then it will show up on the display with a "-" after that and I'd rather avoid that.

            if(key == KeyEvent.VK_SUBTRACT) {
                if(display.getText().isEmpty()) {
                    display.setText("-");
                } else {
                    display.setText("");
                }
            }



I believe the problem is in here. but I can't seem to figure it out.
Was This Post Helpful? 0
  • +
  • -

#5 schutzzz  Icon User is offline

  • D.I.C Regular
  • member icon

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

Re: Key Release

Posted 02 May 2013 - 03:28 PM

Sorry if double posting is frowned upon but I saw no edit button.

But, Problem Fixed!

changed
if(display.getText().isEmpty())



to
if(subBool == false)



thank you guys for your help though, much appreciated!
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1