Results 1 to 7 of 7
  1. #1
    darkkis is offline Member
    Join Date
    Dec 2009
    Posts
    4
    Rep Power
    0

    Thumbs down Keylistenr doesn't work after pressing any button from main aplication

    Hello, please help me to solve one problem with my application. I create simple calculator in java. When I only use the keyboard or only the buttons from app the everything is ok. The problem is that app is not accept keyboard commands after i pressed any button from app.

    My code is attached bellow for more details.
    Thanks for advice.

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    package javaapplication1;
    
    
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.math.BigDecimal;
    import java.math.BigInteger;
    import javax.swing.*;
    
    public class Main {
    	@SuppressWarnings("deprecation")
    	public static void main(String[] args){
    
    		myframe frame=new myframe(10, 10);
    		frame.show();
    	}
    }
    
    	/***************************************Java Frame**************************/
    class myframe extends JFrame{
    
    	private static final long serialVersionUID = 1L;
    
    	public myframe(final int x, final int y){
    
    		setTitle("Calc");
    		setLocation(300, 300);
    		Container pene=getContentPane();
    		mypanel panel= new mypanel();
                    pene.add(panel);
    		pack();
    	}
    }
    	/*********************************************************************************/
    
    	/***************************************Java Panel*******************************/
    class mypanel extends JPanel{
    	private static final long serialVersionUID = 1L;
    	private JLabel display;
    	private JPanel panel;
    	private boolean start;
    	private String lastcommand;
    	keypressed k = new keypressed();
            BigInteger a=new BigInteger("0");
            BigDecimal a1=new BigDecimal("0");
    
    	public mypanel(){
    		start = true;
    		lastcommand="=";
    		//result=0;
    		addKeyListener(k);
    		setLayout(new BorderLayout());
    		//display.setFocusable(true);
    
    		display=new JLabel("0");
    		add(display,BorderLayout.NORTH);
                    display.setFocusable(true);
    		panel = new JPanel();
    		panel.setLayout(new GridLayout(5,4));
    		addbutton("7", 0); addbutton("8", 0); addbutton("9", 0); addbutton("/", 1);
    		addbutton("4", 0); addbutton("5", 0); addbutton("6", 0); addbutton("*", 1);
    		addbutton("1", 0); addbutton("2", 0); addbutton("3", 0); addbutton("-", 1);
    		addbutton("0", 0); addbutton(".", 0); addbutton("=", 1);addbutton("+", 1); addbutton("C", 0);
    		add(panel,BorderLayout.CENTER);
    	}
    	/*********************************************************************************/
    
    	/***************************************Create button function*********************/
    	private void addbutton(String s,int i){
    		JButton button = new JButton(s);
    		if(i==0){
    			button.addActionListener(new insertaction());
    		}
    		if(i==1){
    			button.addActionListener(new commandction());
    		}
    		panel.add(button);
    	}
    	/*********************************************************************************/
    
    	/***************************************Action Listeners**************************/
    	private class insertaction implements ActionListener{
    
    		public void actionPerformed(ActionEvent e) {
    			String input=e.getActionCommand();
    			insertact(input);
                            setRequestFocusEnabled(true);
                            display.requestFocus();
                            display.setFocusable(true);
    		}
    	}
    
    	private class commandction implements ActionListener{
    
    		public void actionPerformed(ActionEvent e) {
    			String command=e.getActionCommand();
    			commandact(command);
                            setRequestFocusEnabled(true);
                            display.requestFocus();
                            display.setFocusable(true);
    		}
    	}
    	/*********************************************************************************/
    
    	/********************Reaction to button pressed and calculation*******************/
    
    	public void calculateint(String x){
    		BigInteger b=new BigInteger(x);
    		if(lastcommand.equals("+"))a=a.add(b);
    		else if(lastcommand.equals("-"))a=a.subtract(b);
    		else if(lastcommand.equals("*"))a=a.multiply(b);
    		else if(lastcommand.equals("/"))a=a.divide(b);
    		else if(lastcommand.equals("="))a=b;
    		String res=""+a;
    		setdisplay(res);
                     // panel.requestFocusInWindow();
    		}
    
            public void calculatedoub(String x){
    		BigDecimal b1=new BigDecimal(x);
    		if(lastcommand.equals("+"))a1=a1.add(b1);
    		else if(lastcommand.equals("-"))a1=a1.subtract(b1);
    		else if(lastcommand.equals("*"))a1=a1.multiply(b1);
    		else if(lastcommand.equals("/"))a1=a1.divide(b1);
    		else if(lastcommand.equals("="))a1=b1;
    		String res=""+a1;
    		setdisplay(res);
                     // panel.requestFocusInWindow();
    		}
    
            public void insertact (String input){
    
    		if(input.equals("C"))display.setText("0");
    		if(start){
    			if(!display.getText().equals("-"))setdisplay("");
    			start=false;
                            }
    		if(display.getText().equals("")&&(input.equals(".")))display.setText("0.");
    		if(!input.equals(".")||(display.getText().lastIndexOf(".")<0))
    			if(!input.equals("C"))
    				if(!display.getText().startsWith("0"))setdisplay(display.getText()+input);
    				else {
    					setdisplay("0");
    					start = true;
    					lastcommand="=";
    					}
                     //panel.requestFocusInWindow();
    		}
                    
             public void commandact (String command){
    		if(start){
    			if(command.equals("-")){
    				setdisplay(command);
    				start=false;
    			}
    			else lastcommand=command;
                        }
                        else
                        {
                        if(!display.getText().equals("-"))
                                if(!display.getText().contains("."))
                                    	calculateint(display.getText());
                                else calculatedoub(display.getText());
                        lastcommand=command;
                        start=true;
                        }
                     // panel.requestFocusInWindow();
    		}
    
    	public void setdisplay(String text){
    		display.setText(text);
                    //panel.requestFocusInWindow();
    	}
    	/*********************************************************************************/
    
    	/*********************************Key listener************************************/
    	private class keypressed implements KeyListener{
    
    		public void keyPressed(KeyEvent e) {
    			int kk=e.getKeyCode();
    			if (kk==KeyEvent.VK_ENTER)commandact("=");
    			if (kk==KeyEvent.VK_ESCAPE)insertact("C");
    		}
    
    		public void keyReleased(KeyEvent arg0) {
    		}
    
    		public void keyTyped(KeyEvent e) {
    			char key=e.getKeyChar();
    			switch(key){
    			case '0':insertact("0");break;
    			case '1':insertact("1");break;
    			case '2':insertact("2");break;
    			case '3':insertact("3");break;
    			case '4':insertact("4");break;
    			case '5':insertact("5");break;
    			case '6':insertact("6");break;
    			case '7':insertact("7");break;
    			case '8':insertact("8");break;
    			case '9':insertact("9");break;
    			case '.':insertact(".");break;
    			case 'c':insertact("C");break;
    			case '+':commandact("+");break;
    			case '-':commandact("-");break;
    			case '*':commandact("*");break;
    			case '/':commandact("/");break;
    			case '=':commandact("=");break;
    			}
    		}
    	}
      }
    /*********************************************************************************/

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,234
    Rep Power
    7

    Default

    > When I only use the keyboard or only the buttons from app the everything is ok. The problem is that app is not accept keyboard commands after i pressed any button from app.

    Thats because KeyStrokes are dispatched to the component with focus. Once you click a button the panel no longer has focus to it doesn't receive the KeyEvents.

    The solution is to use KeyBindings. Read the section from the Swing tutorial on "How to Use Key Bindings" for more information.

  3. #3
    darkkis is offline Member
    Join Date
    Dec 2009
    Posts
    4
    Rep Power
    0

    Default Negative BigInteger and BigDecimal

    Thanks for information, that was helpfull :) but i have some additional question.
    Can the BigInteger and BigDecimal numbers be negative (with "-" sign)? If yes then please show me an example.

    Thanks a lot.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Can the BigInteger and BigDecimal numbers be negative(with "-" sign)?
    1) Yes they can be negative.
    2) The negative sign doesn't have much to do with the number itself but mainly has to do with displaying the number.

    If yes then please show me an example.
    3) It's not all that complex:
    Java Code:
          BigInteger myBigInt = new BigInteger("-25");
          System.out.println(myBigInt);
    If you have a similar problem in the future, you may want to try it first yourself and then post this attempt with your question.
    Last edited by Fubarable; 12-23-2009 at 03:22 AM.

  5. #5
    darkkis is offline Member
    Join Date
    Dec 2009
    Posts
    4
    Rep Power
    0

    Default Negative BigInteger and BigDecimal

    Thanks, I understud how it is created, but when i try to make "substract" operation then for result I get "0". For more details see bellow example.

    Java Code:
    BigInteger a = new BigInteger("-123");
    BigInteger b = new BigInteger("-124");
    System.out.println(""+a.subtract(b));
    Can be made substract operation with two negative BigIntegers?
    Last edited by darkkis; 12-23-2009 at 08:29 AM.

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by darkkis View Post
    Thanks, I understud how it is created, but when i try to make "substract" operation then for result I get "0". For more details see bellow example.

    Java Code:
    BigInteger a = new BigInteger("-123");
    BigInteger b = new BigInteger("-124");
    System.out.println(""+a.subtract(b));
    Can be made substract operation with two negative BigIntegers?
    Strange, because when I run your code snippet I get this:

    Java Code:
    1
    ... as it should be.

    kind regards,

    Jos

  7. #7
    darkkis is offline Member
    Join Date
    Dec 2009
    Posts
    4
    Rep Power
    0

    Default

    :o ups i forgot some main function in math. Thanks for answer

Similar Threads

  1. mysql connect button doesnt work quite right
    By 711groove in forum New To Java
    Replies: 0
    Last Post: 12-13-2009, 07:01 AM
  2. Hibernate aplication Problem
    By Prashant.surwade in forum Advanced Java
    Replies: 6
    Last Post: 09-18-2009, 10:32 AM
  3. Replies: 2
    Last Post: 04-12-2009, 10:39 AM
  4. Replies: 2
    Last Post: 03-26-2009, 04:15 AM
  5. Replies: 5
    Last Post: 01-17-2008, 09:01 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •