0

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...

3
Contributors
5
Replies
7
Views
10 Years
Discussion Span
Last Post by phamvantu_ctk30
0

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);
    }
}

Edited by mike_2000_17: Fixed formatting

0

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.

0

Đầu tiên cho Focus cái JPanel rùi cho nó lắng nghe KeyListener trên chínhd nó là OK.

this.setFocusable(true);
this.addKeyListener((KeyListener)this);

package AppKeyListener;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class MyPanel extends JPanel implements KeyListener {
    public MyPanel(){
        super();
        this.setBackground(Color.gray);
        this.setFocusable(true);  
        this.addKeyListener((KeyListener)this);
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        g.fillRect(x, y, 100, 50);
    }
    int x=100,y=50;
    Color color=Color.red;
    
// Main method

    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frm =new JFrame("App Key Listener");
        frm.setSize(400, 300);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setVisible(true);
        MyPanel p =new MyPanel();
        frm.add(p);        
    }
    public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyChar()=='g')
            color=Color.GREEN;
        if(e.getKeyChar()=='r')
            color=Color.red;
        if(e.getKeyChar()=='b')
            color=Color.blue;
        if(e.getKeyChar()=='y')
            color=Color.yellow;
        if(e.getKeyChar()=='w')
            color=Color.WHITE;
        if(e.getKeyCode()==KeyEvent.VK_UP)
            y-=2;
        if(e.getKeyCode()==KeyEvent.VK_DOWN)
            y+=2;
        if(e.getKeyCode()==KeyEvent.VK_RIGHT)
            x+=2;
        if(e.getKeyCode()==KeyEvent.VK_LEFT)
            x-=2;
        this.repaint();
    }
    public void keyReleased(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}
0

Add KeyListener on Jpanel:

Focus JPanel and add KeyListener on its. OK.hjhj

this.setFocusable(true);
this.addKeyListener((KeyListener)this);

package AppKeyListener;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class MyPanel extends JPanel implements KeyListener {
    public MyPanel(){
        super();
        this.setBackground(Color.gray);
        this.setFocusable(true);  
        this.addKeyListener((KeyListener)this);
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(color);
        g.fillRect(x, y, 100, 50);
    }
    int x=100,y=50;
    Color color=Color.red;
    
// Main method

    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frm =new JFrame("App Key Listener");
        frm.setSize(400, 300);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setVisible(true);
        MyPanel p =new MyPanel();
        frm.add(p);        
    }
    public void keyTyped(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyChar()=='g')
            color=Color.GREEN;
        if(e.getKeyChar()=='r')
            color=Color.red;
        if(e.getKeyChar()=='b')
            color=Color.blue;
        if(e.getKeyChar()=='y')
            color=Color.yellow;
        if(e.getKeyChar()=='w')
            color=Color.WHITE;
        if(e.getKeyCode()==KeyEvent.VK_UP)
            y-=2;
        if(e.getKeyCode()==KeyEvent.VK_DOWN)
            y+=2;
        if(e.getKeyCode()==KeyEvent.VK_RIGHT)
            x+=2;
        if(e.getKeyCode()==KeyEvent.VK_LEFT)
            x-=2;
        this.repaint();
    }
    public void keyReleased(KeyEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}

Edited by phamvantu_ctk30: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.