Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 86,390 Java Programmers. There are 1,371 online right now! Ask your question and get quick answers from Dream.In.Code experts. Join the #1 programming help community on the internet! Registration is fast and FREE... Join Now!

Chat LIVE With a Java Expert
Powered by LivePerson.com

Register to Make This Box Go Away!

Capturing pressed key anywhere in program window

 
Reply to this topicStart new topic

Capturing pressed key anywhere in program window

Unknown Hero
post 7 May, 2008 - 03:44 PM
Post #1


New D.I.C Head

*
Joined: 4 Sep, 2007
Posts: 8



Hell everybody!

I'm makeing my own calculator (as homework). It uses reversed polish notation (http://en.wikipedia.org/wiki/Reverse_Polish_notation).
Quick explanation of RPN:
You first have to type both numbers, then you can type mathematical operation.
Example:
5
ENTER
16
ENTER
+

(this will write 21 in label)


My program works well if you use buttons. However, I can't make my program to recognize numbers I press using keyboard. I have made new KeyListener (k), but don't know where to add it.
I tried
addKeyListener(k);
and
this.getContentPane.addKeyListener(k);
and
(Label) kutija.addKeyListener(k);
and
(Panel) panel.addKeyListener(k);
but none works.

Here's code. I really appreciate your help!
Simple explanation of the code:
I use BorderLayout.
I have label where I write numbers user presses (BorderLayout.PAGE_START) and panel (GridLayout (4, 5)) for buttons (BorderLayout.CENTER).

CODE
package vjezba;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Stack;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class Calculator extends JFrame
{
    
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private Stack<Double> stog;
    private JLabel kutija;
    private boolean moze;
    private boolean tocka;
    private boolean cos1;
    private boolean cos2;
    private boolean sin1;
    private boolean sin2;
    
    public Calculator ()
    {
        super();
        stog = new Stack<Double>();
        initGUI();
    }
    
    protected void initGUI()
    {
        cos1 = cos2 = sin1 = sin2 = false;
        moze = true;
        tocka = false;
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setSize(400, 250);
        setLocation(40, 40);
        setTitle("Digic");
        this.getContentPane().setLayout(new BorderLayout());
        
        kutija = new JLabel("0");
        kutija.setHorizontalAlignment(SwingConstants.RIGHT);
        kutija.setVerticalAlignment(SwingConstants.CENTER);
        kutija.setPreferredSize(new Dimension(50, 50));
        this.getContentPane().add(kutija, BorderLayout.PAGE_START);
        
        KeyListener k = new KeyListener()
        {
            public void keyTyped(KeyEvent arg0)
            {}
            
            public void keyReleased(KeyEvent arg0)
            {}
            
            public void keyPressed(KeyEvent arg0)
            {
                char c = arg0.getKeyChar();
                if (Character.isDigit(c))
                    System.out.println("slovo");
                else if (c == '+' || c == '-' || c == '*' || c == '/')
                {
                    operacija(c);
                }
                else if (c == 'c')
                    cos1 = true;
                else if (c == 'o')
                {
                    if (cos1)
                        cos2 = true;
                }
                else if (c == 's')
                {
                    if (cos1 && cos2)
                    {
                        cos1 = false;
                        cos2 = false;
                        operacijaTwo("cos");
                    }
                    else
                        sin1 = true;
                }
                else if (c == 'i')
                {
                    if (sin1)
                        sin2 = true;
                }
                else if (c == 'n')
                {
                    if (sin1 && sin2)
                        operacijaTwo("sin");
                }
            }
        };
        
        JPanel panel = new JPanel(new GridLayout(4, 5));
        JButton gumb = new JButton("7");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(7);
            }
        });
        
        gumb = new JButton("8");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(8);
            }
        });
        
        gumb = new JButton("9");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(9);
            }
        });
        
        gumb = new JButton("DEL");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (kutija.getText().equals("Niste unijeli dovoljno brojeva!")
                        || kutija.getText().length() == 1 || moze)
                {
                    kutija.setText("0");
                    moze = true;
                }
                else if (kutija.getText().length() > 1)
                    kutija.setText(new String(kutija.getText().substring(0,
                            kutija.getText().length() - 1)));
            }
        });
        
        gumb = new JButton("/");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                operacija('/');
            }
        });
        
        gumb = new JButton("4");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(4);
            }
        });
        
        gumb = new JButton("5");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(5);
            }
        });
        
        gumb = new JButton("6");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(6);
            }
        });
        
        gumb = new JButton("RESET");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                stog.clear();
                kutija.setText("0");
                moze = true;
                tocka = false;
            }
        });
        
        gumb = new JButton("*");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                operacija('*');
            }
        });
        
        gumb = new JButton("1");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(1);
            }
        });
        
        gumb = new JButton("2");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(2);
            }
        });
        
        gumb = new JButton("3");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(3);
            }
        });
        
        gumb = new JButton("sin");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                operacijaTwo("sin");
            }
        });
        
        gumb = new JButton("-");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                operacija('-');
            }
        });
        
        gumb = new JButton("0");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                akcija(0);
            }
        });
        
        gumb = new JButton(".");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if (!tocka)
                {
                    tocka = true;
                    if (!moze)
                        kutija.setText(kutija.getText() + ".");
                    else
                    {
                        kutija.setText("0.");
                        moze = false;
                    }
                }
            }
        });
        
        gumb = new JButton("ENTER");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                if (!moze)
                {
                    stog.push(Double.parseDouble(kutija.getText()));
                    moze = true;
                    tocka = false;
                }
            }
        });
        
        gumb = new JButton("cos");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                operacijaTwo("cos");
            }
        });
        
        gumb = new JButton("+");
        panel.add(gumb);
        gumb.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                operacija('+');
            }
        });
        
        this.getContentPane().add(panel, BorderLayout.CENTER);
        
        setVisible(true);
    }
    
    private void operacija(char c)
    {
        if (stog.size() > 1)
        {
            double broj = stog.pop();
            double broj2 = stog.pop();
            double rez;
            if (c == '*')
                rez = broj2 * broj;
            else if (c == '+')
                rez = broj2 + broj;
            else if (c == '-')
                rez = broj2 + broj;
            else
                rez = broj2 / broj;
            stog.push(rez);
            kutija.setText(((Double)rez).toString());
        }
        else
        {
            kutija.setText("Niste unijeli dovoljno brojeva!");
            moze = true;
            tocka = false;
        }
    }
    
    private void operacijaTwo(String str)
    {
        if (!stog.empty())
        {
            moze = true;
            if (str.equals("cos"))
                stog.push(Math.cos(stog.pop()));
            else
                stog.push(Math.sin(stog.pop()));
            kutija.setText(stog.peek().toString());
        }
        else
        {
            kutija.setText("Niste unijeli dovoljno brojeva!");
            moze = true;
            tocka = false;
        }
    }
    
    protected void akcija(int i)
    {
        if (moze)
            kutija.setText(((Integer)i).toString());
        else if (!tocka)
            kutija.setText(kutija.getText() + i);
        else
            kutija.setText(kutija.getText() + i);
        if (!kutija.getText().equals("0"))
            moze = false;
    }
    
}



Main class with main method:
CODE
package hr.fer.zemris.java.tecaj_6.vjezba;

import java.lang.reflect.InvocationTargetException;

import javax.swing.SwingUtilities;

public class Main
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                public void run()
                {
                    new Calculator();
                }
            });
        } catch (InvocationTargetException e)
        {} catch (InterruptedException e)
        {}
    }
}


Thank you!
User is offlineProfile CardPM
Go to the top of the page
+Quote Post


pbl
post 7 May, 2008 - 04:02 PM
Post #2


D.I.C Addict

Group Icon
Joined: 6 Mar, 2008
Posts: 849

panel.addKeyListener(k);
is what you have to do

Thank God there are still people using RPL calculators
Anybody has an HP16C for sale ?

Already answered that question

http://www.dreamincode.net/forums/index.ph...p;hl=tabbedpane

This post has been edited by pbl: 7 May, 2008 - 04:04 PM
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Unknown Hero
post 7 May, 2008 - 04:06 PM
Post #3


New D.I.C Head

*
Joined: 4 Sep, 2007
Posts: 8

QUOTE(pbl @ 7 May, 2008 - 04:02 PM) *

panel.addKeyListener(k);
is what you have to do

Thank God there are still people using RPL calculators
Anybody has an HP16C for sale ?

Already answered that question

http://www.dreamincode.net/forums/index.ph...p;hl=tabbedpane


QUOTE

My program works well if you use buttons. However, I can't make my program to recognize numbers I press using keyboard. I have made new KeyListener (k), but don't know where to add it.
I tried
addKeyListener(k);
and
this.getContentPane.addKeyListener(k);
and
(Label) kutija.addKeyListener(k);
and
(Panel) panel.addKeyListener(k);
but none works.


As I already said, it doesn't work.

Panel is added to BorderLayout.CENTER, it's not the whole window.
Try running this program on your own machine. You will be able to easily realise what's happening.

This post has been edited by Unknown Hero: 7 May, 2008 - 04:08 PM
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

pbl
post 7 May, 2008 - 04:10 PM
Post #4


D.I.C Addict

Group Icon
Joined: 6 Mar, 2008
Posts: 849

OK I'll try
give me few minutes
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

pbl
post 7 May, 2008 - 04:27 PM
Post #5


D.I.C Addict

Group Icon
Joined: 6 Mar, 2008
Posts: 849

QUOTE(pbl @ 7 May, 2008 - 04:10 PM) *

OK I'll try
give me few minutes


If you want to have the keyListenr to work on any JComponent that has the FOCUS you will have to add it to all of them

CODE

        JButton gumb = new JButton("7");
        gumb.addKeyListener(k);


or check that:

http://java.sun.com/docs/books/tutorial/ui...keybinding.html

or use the class and code already posted
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Unknown Hero
post 8 May, 2008 - 05:20 PM
Post #6


New D.I.C Head

*
Joined: 4 Sep, 2007
Posts: 8

It worked!

Thank you very much! smile.gif
User is offlineProfile CardPM
Go to the top of the page
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 5/17/08 04:57AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month