User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 456,504 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,683 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 1848 | Replies: 3
Reply
Join Date: Feb 2007
Location: Phil..
Posts: 18
Reputation: talablink is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 1
talablink's Avatar
talablink talablink is offline Offline
Newbie Poster

Question keylistener

  #1  
Sep 27th, 2007
how do you add a key listener to a java GUI?
can anyone pls show me how...
or at least give an example..pls

cause I want to add a key listener to my GUI calculator
but I don't now how or where to put it and stuff...

thanks...
AddThis Social Bookmark Button
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 3,090
Reputation: Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold 
Rep Power: 15
Solved Threads: 307
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Posting Sensei

Re: keylistener

  #2  
Sep 27th, 2007
Sun's tutorial is a good palce to start.
Tutorial: Writing a Key Listener
If you still have unanswered questions after that, just post them here
Reply With Quote  
Join Date: Feb 2007
Location: Phil..
Posts: 18
Reputation: talablink is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 1
talablink's Avatar
talablink talablink is offline Offline
Newbie Poster

Re: keylistener

  #3  
Sep 27th, 2007
my key listener is on the last part...and i don't know what to do with it...
i'm suppose to add a key listener to this code...

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

import java.awt.event.KeyEvent;




class CalcGUI extends JPanel {


    //=============================================== instance variables
    //--- variable for GUI elements
    private JTextField _displayField;        // display result / input.
    //--- variables representing state of the calculator
    private boolean    _startNumber = true;  // true: num key next
    private double        _resultValue = 0.0;     // result so far
    private String     _previousOp  = "=";   // previous operation
    //end instance variables

    //-------------------------------------------- static (class) variables
    private static final Font BIGGER_FONT = new Font("monspaced",
 Font.PLAIN, 24);


    //======================================================constructor
    public CalcGUI() {
        //--- Display field
        _displayField = new JTextField("0", 12);
        _displayField.setHorizontalAlignment(JTextField.RIGHT);
        _displayField.setFont(BIGGER_FONT);
        

        //--- Clear button
        JButton clearButton = new JButton("CLEAR");
        clearButton.setFont(BIGGER_FONT);
        clearButton.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    action_clear();
                }
            }
        );

        //--- Use one listener for all numeric keys.
        ActionListener numListener =
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    action_num(e);  // process it below
                }
            };

        //--- Layout numeric keys in a grid.
        //--- Use the characters in a string as a guide
        //--- for producing the numeric keys.
        String buttonOrder = "789456123 0 ";
        JPanel buttonPanel = new JPanel(new GridLayout(5, 3));
        for (int i = 0; i < buttonOrder.length(); i++) {
            String keyTop = buttonOrder.substring(i, i+1);
            if (keyTop.equals(" ")) {
                buttonPanel.add(new JLabel(""));
            } else {
                JButton b = new JButton(keyTop);
                b.addActionListener(numListener);
                b.setFont(BIGGER_FONT);
                buttonPanel.add(b);
            }
        }

        //--- Create an ActionListener that will be used for
        //--- all of the operator buttons.
        ActionListener opListener =
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                   action_op(e);
                }//endmethod actionPerformed
           };


        //--- Create panel with gridlayout to hold operator buttons.
        //--- Use array of button names to create buttons in a loop.
        JPanel opPanel = new JPanel(new GridLayout(5, 1));
        String[] opOrder = {"+", "-", "*", "/", "=","%"};
        for (int i = 0; i < opOrder.length; i++) {
            JButton b = new JButton(opOrder[i]);
            b.addActionListener(opListener);
            b.setFont(BIGGER_FONT);
            opPanel.add(b);
            }
            JButton c= new JButton(".");
            c.setFont(BIGGER_FONT);
            opPanel.add(c);

        /**c.addKeyListener( new KeyListener (){
                public void keyPressed( KeyEvent e){
                    _displayField.setText(".");
                }
                });*/

         


        //--- Layout this, the top level, panel.
        this.setLayout(new BorderLayout());
        this.add(_displayField, BorderLayout.NORTH );
        this.add(buttonPanel  , BorderLayout.CENTER);
        this.add(opPanel      , BorderLayout.EAST  );
        this.add(clearButton  , BorderLayout.SOUTH );
         this.add(MyPanel, BorderLayout.SOUTH);     
    }//end constructor


    //============================================================ action_op
    // Called by the action listener for all op buttons.
    private void action_op(ActionEvent e) {
        // The calculator is always in one of two states.
        // 1. A number must be entered next (so this operator is wrong).
        // 2. An operator must be entered next (so we're ok).
        if (_startNumber) { // Error: needed number, not operator
            action_clear();
            _displayField.setText("ERROR");
        } else {
            _startNumber = true;  // Next thing must be a number
            try {
                // Get the value from display field, convert it, do prev op
                // If this is the first op, _previousOp will be =.
                int currentValue =
 Integer.parseInt(_displayField.getText());
                double currentValuez = Double.parseDouble(_displayField.getText());
                //int d=Integer.parseInt(c);

                if (_previousOp.equals("=")) {
                    _resultValue = currentValue;
                } else if (_previousOp.equals("+")) {
                    _resultValue += currentValuez;
                } else if (_previousOp.equals("-")) {
                    _resultValue -= currentValuez;
                } else if (_previousOp.equals("*")) {
                    _resultValue *= currentValuez;
                } else if (_previousOp.equals("/")) {
                    _resultValue /= currentValue;
                } else if (_previousOp.equals("%")) {
                    _resultValue %= currentValue;
                }

                _displayField.setText(""+_resultValue);

            } catch (NumberFormatException ex) {
                action_clear();
                _displayField.setText("Error");
            }

            //--- set _previousOp for the next operator.
            _previousOp = e.getActionCommand();
        }//endif _startNumber
    }//endmethod action_op


    //======================================================== action_num
    // Called by the action listener for numeric keys
    private void action_num(ActionEvent e) {
        String digit = e.getActionCommand(); // gets text from digitkey
        if (_startNumber) {
            // This is the first digit, clear field and set
            _displayField.setText(digit);
            _startNumber = false;
        } else {
            // Add this digit to the end of the display field
            _displayField.setText(_displayField.getText() + digit);
        }
    }//endmethod action_num


    //=============================================== logic action_clear
    // Called by the action listener for the Clear button
    public void action_clear() {
        _startNumber = true;
        _displayField.setText("0");
        _resultValue = 0.0;
        _previousOp  = "=";




    }//endmethod action_clear

}//endclass CalcGUI

class MyPanel extends JPanel implements KeyListener{
        
    public MyPanel(){
        this.setFocusable(true);
        this.addKeyListener(this);
    }
    
    public void keyTyped(KeyEvent e){
         char i = e.getKeyChar();
         System.out.println("Key Typed: " + i);
    }
    
    public void keyPressed(KeyEvent e){
         char i = e.getKeyChar();
         System.out.println("Key Pressed: " + i);
    }
    public void keyReleased(KeyEvent e){
         char i = e.getKeyChar();
         System.out.println("Key Released: " + i);
    }
}

Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 3,090
Reputation: Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold Ezzaral is a splendid one to behold 
Rep Power: 15
Solved Threads: 307
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Posting Sensei

Re: keylistener

  #4  
Sep 27th, 2007
Why does your listener need to extend JPanel? Your class can just implement KeyListener or extend KeyAdapter and be added to a component with the .addKeyListener( new MyListener() ) call. When a key is pressed in that component, the listener will fire and you process it accordingly.
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

DaniWeb Java Marketplace
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

Thread Tools Display Modes

Similar Threads
Other Threads in the Java Forum

All times are GMT -4. The time now is 3:37 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC