Closed Thread
Results 1 to 5 of 5

Thread: Assign a keyboard key to a JButton.

  1. #1
    gszauer's Avatar
    gszauer is offline Programmer
    Join Date
    Nov 2007
    Location
    Florida
    Posts
    113
    Rep Power
    16

    Assign a keyboard key to a JButton.

    So, i need some help
    I want to press a key, and invoke the action of a coresponding button.
    So, for instance, if i press the key 1, i would like my jbutton (button[1]) to "be pressed"

    Here is the keyboard scanning code i wrote
    [HIGHLIGHT="Java5"]public void keyReleased(KeyEvent e){
    }

    public void keyTyped(KeyEvent e){
    }

    public void keyPressed (KeyEvent e){
    keyID = e.getID();
    if (keyID == 97 || keyID == 49){
    // 1
    } else if (keyID == 98 || keyID == 50){
    // 2
    } else if (keyID == 99 || keyID == 51){
    // 3
    } else if (keyID == 100 || keyID == 52){
    // 4
    } else if (keyID == 101 || keyID == 53){
    // 5
    } else if (keyID == 102 || keyID == 54){
    // 6
    } else if (keyID == 103 || keyID == 55){
    // 7
    } else if (keyID == 104 || keyID == 56){
    // 8
    } else if (keyID == 105 || keyID == 57){
    // 9
    } else if (keyID == 110 || keyID == 46){
    // .
    } else if (keyID == 10){
    // =
    } else if (keyID == 107){
    // +
    } else if (keyID == 109){
    // -
    } else if (keyID == 106){
    // *
    } else if (keyID == 111){
    // /
    } else if (keyID == 67){
    // C
    }
    JOptionPane.showMessageDialog(null, keyID+" Was Pressed", "Exception Error", JOptionPane.INFORMATION_MESSAGE);
    }[/HIGHLIGHT]

    My class is
    [HIGHLIGHT="Java5"]public class Calculator extends JFrame implements ActionListener, KeyListener {[/HIGHLIGHT]

    So i have
    [HIGHLIGHT="Java5"]this.addKeyListener(this);[/HIGHLIGHT]

    But when i press a key i am not informed that a key was pressed by the JOptionPane, so i take im not doing something right.

    ALSO, once i have it so where its listening for keypresses correctly, how can i get it to "Press" certin buttons for me?
    For instance, where my code has //C I would like for it to execute the action that i execute when the JButton calculate = new JButton("C"); button is pressed....

    Can anyone offer any guidance?
    Quote Originally Posted by ~Aristotle
    It is the mark of an educated mind to entertain a tought without accepting it
    If my post was helpful, please help me build some rep

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    domestic's Avatar
    domestic is offline Learning Programmer
    Join Date
    Mar 2007
    Location
    SCOTLAND!
    Posts
    44
    Rep Power
    0
    Get key. This bassically monitors the jframe (you called it Calculator), and runs everytime a key is pressed. It then stores the value in variable ke for easy access. It will then go through list to see what the value means.

    NB: requires importing of String

    [HIGHLIGHT="Java"]
    private void Calculator(java.awt.event.KeyEvent evt) {
    int ke = evt.getKeyCode();

    if (ke==10) String keypress = "Enter";
    else if......etc etc; < insert your keyevent codes here


    JOptionPane.showMessageDialog(null, "key pressed was " keypress, "key pressed", JOptionPane.INFORMATION_MESSAGE);
    }
    [/HIGHLIGHT]
    .


    Programming Languages: Java, VB6, VB2005 (.NET2)
    Web Languages: HTML, CSS, JS

    Website: http://abdn.ac.uk/~u41am6

    Opportunity is missed by most people because it is dressed in overalls and looks like work.

  4. #3
    Join Date
    Oct 2007
    Posts
    538
    Rep Power
    21
    You first need to attach a KeyListener to the object though. That method won't get called otherwise.

    //edit - sorry didn't see there was already a KeyListener. My bad.//
    Last edited by G_Morgan; 01-07-2008 at 09:11 AM.

  5. #4
    domestic's Avatar
    domestic is offline Learning Programmer
    Join Date
    Mar 2007
    Location
    SCOTLAND!
    Posts
    44
    Rep Power
    0
    very easy if you use netbeans. just select the form, choose events and then keylistener. puts in all the extra code. don't know if any other programs do this too though. only used nb and blueJ
    .


    Programming Languages: Java, VB6, VB2005 (.NET2)
    Web Languages: HTML, CSS, JS

    Website: http://abdn.ac.uk/~u41am6

    Opportunity is missed by most people because it is dressed in overalls and looks like work.

  6. #5
    gszauer's Avatar
    gszauer is offline Programmer
    Join Date
    Nov 2007
    Location
    Florida
    Posts
    113
    Rep Power
    16
    Sorry for the delay in response, i had some stuff to take care of.
    While i was gone i actually solved the problem myself, here is how:

    [HIGHLIGHT="Java5"]import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    public class Calculator extends JFrame implements ActionListener, KeyListener {
    private int width, height, keyID;
    private double num1, num2, temp;
    private char operation = 'x', operator;
    private boolean isFirst = true, hasDecimal = false;
    private String buffer;
    private String[] labels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", "+/-", ".", "+"};
    private JButton[] buttons;
    private JButton calculate, clear;
    private JTextField output;

    public Calculator (){
    Container pane = getContentPane();
    pane.setLayout(null);

    output = new JTextField();
    output.setEditable(false);
    output.setLocation (5, 5);
    output.setSize(215, 20);
    output.setHorizontalAlignment(JTextField.RIGHT);
    pane.add(output);

    buttons = new JButton[16];
    width = 5; height = 30;
    for (int i = 0; i < labels.length; i++){
    buttons[i] = new JButton(labels[i]);
    buttons[i].addActionListener(this);
    buttons[i].addKeyListener(this);
    buttons[i].setSize(50, 25);
    buttons[i].setLocation(width, height);
    pane.add(buttons[i]);

    width +=55;
    if (width >= 200) {
    width = 5;
    height +=30;
    }
    }
    calculate = new JButton("=");
    calculate.setSize(160, 25);
    calculate.setLocation(5, 150);
    calculate.addActionListener(this);
    calculate.addKeyListener(this);
    pane.add(calculate);

    clear = new JButton("C");
    clear.setSize(50, 25);
    clear.setLocation(170, 150);
    clear.addActionListener(this);
    clear.addKeyListener(this);
    pane.add(clear);


    width = 241; height = 216;
    setTitle("Java Calculator");
    setSize(width, height);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setIconImage(new ImageIcon("icon.png").getImage());
    setFocusable(true);
    addKeyListener(this);
    pane.setFocusable(true);
    pane.addKeyListener(this);
    reset();
    }

    public void actionPerformed (ActionEvent e){
    if (e.getActionCommand().equals("+/-")) {
    performAction('q');
    } else {
    performAction(e.getActionCommand().charAt(0));
    }
    }

    public void performAction(char action){
    try {
    switch (action) {
    case '0':
    case '1':
    case '2':
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9':
    if (isFirst){
    output.setText(""+action);
    isFirst = false;
    } else {
    buffer = output.getText();
    output.setText(buffer+action);
    }
    break;
    case 'q':
    temp = Double.parseDouble(output.getText());
    if (temp < 0) {
    temp = Math.abs(temp);
    } else if (temp > 0){
    temp = -temp;
    } else if (temp == 0){
    }
    output.setText(""+temp);
    break;
    case '.':
    buffer = output.getText();
    if (buffer.indexOf(".") < 0){
    output.setText(buffer+".");
    } else {
    if (buffer.charAt(buffer.indexOf(".")+1) == '0')
    output.setText(buffer.substring(0, (buffer.indexOf(".")+1)));
    isFirst = false;
    }
    break;
    case 'C':
    reset();
    break;
    case '+':
    case '-':
    case '*':
    case '/':
    num1 = Double.parseDouble(output.getText());
    operation = action;
    isFirst = true;
    break;
    case '=':
    num2 = Double.parseDouble(output.getText());
    if (operation == '+') num1 += num2;
    if (operation == '-') num1 -= num2;
    if (operation == '*') num1 *= num2;
    if (operation == '/') num1 /= num2;
    if (operation == 'x') num1 = Double.parseDouble(output.getText());
    reset (""+num1);
    break;
    }
    } catch (ArithmeticException ae){
    JOptionPane.showMessageDialog(null, "ERROR: An Unknown Exception Has Occured\n"+ae.getMessage(), "Exception Error", JOptionPane.INFORMATION_MESSAGE);
    reset();
    }catch (Exception ee){
    JOptionPane.showMessageDialog(null, "ERROR: An Unknown Exception Has Occured\n"+ee.getMessage(), "Exception Error", JOptionPane.INFORMATION_MESSAGE);
    reset();
    }
    }

    public void reset(){
    num1 = 0;
    num2 = 0;
    reset ("0.0");
    }

    public void reset(String init){
    isFirst = true;
    operation = 'x';
    output.setText (init);
    }

    public void keyReleased(KeyEvent e){
    }

    public void keyTyped(KeyEvent e){
    }

    public void keyPressed (KeyEvent e){
    //keyID = e.getID();
    keyID = e.getKeyChar();
    if (keyID == 97 || keyID == 49){
    // 1
    performAction('1');
    } else if (keyID == 98 || keyID == 50){
    // 2
    performAction('2');
    } else if (keyID == 99 || keyID == 51){
    // 3
    performAction('3');
    } else if (keyID == 100 || keyID == 52){
    // 4
    performAction('4');
    } else if (keyID == 101 || keyID == 53){
    // 5
    performAction('5');
    } else if (keyID == 102 || keyID == 54){
    // 6
    performAction('6');
    } else if (keyID == 103 || keyID == 55){
    // 7
    performAction('7');
    } else if (keyID == 104 || keyID == 56){
    // 8
    performAction('8');
    } else if (keyID == 105 || keyID == 57){
    // 9
    performAction('9');
    } else if (keyID == 110 || keyID == 46){
    // .
    performAction('.');
    } else if (keyID == 10){
    // =
    performAction('=');
    } else if (keyID == 107 || keyID == 43){
    // +
    performAction('+');
    } else if (keyID == 109 || keyID == 45){
    // -
    performAction('-');
    } else if (keyID == 106 || keyID == 42){
    // *
    performAction('*');
    } else if (keyID == 111 || keyID == 47){
    // /
    performAction('/');
    } else if (keyID == 67 || keyID == 99){
    // C
    performAction('C');
    } else if (keyID == 48){
    // 0
    performAction('0');
    }
    //JOptionPane.showMessageDialog(null, keyID+" Was Pressed", "Debug Information", JOptionPane.INFORMATION_MESSAGE);
    }
    }[/HIGHLIGHT]

    But im going to re-write it, my code is not pretty at all....
    Last edited by gszauer; 01-08-2008 at 12:11 PM.
    Quote Originally Posted by ~Aristotle
    It is the mark of an educated mind to entertain a tought without accepting it
    If my post was helpful, please help me build some rep

Closed Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Manually Assign a Resource WPF
    By sp3tsnaz in forum C# Programming
    Replies: 0
    Last Post: 08-04-2011, 01:14 AM
  2. Replies: 1
    Last Post: 03-26-2011, 06:15 PM
  3. help needed to assign score to words
    By Rahul Dev in forum PHP Development
    Replies: 1
    Last Post: 12-18-2010, 04:26 AM
  4. How to assign an address
    By Hunter100 in forum HTML Programming
    Replies: 3
    Last Post: 05-07-2010, 11:50 PM
  5. Assign variable values with a file?
    By FrozenSnake in forum C and C++
    Replies: 2
    Last Post: 04-09-2009, 08:27 AM

Tags for this Thread

Bookmarks

Posting Permissions

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