How to make a simple keypad on java to input in JTextFields efficiently?

razshan picture razshan · Nov 9, 2010 · Viewed 9.3k times · Source

I am working on a keypad on java that will be used to input data in two JTextField (x & y). And Once the user clicks "Enter", It should evaluate the difference of x and y. Do I have to add bunch of actionListeners for each button?? Is there an efficient way to do it.

So far on my code, I have all the buttons I need, but instead of using my keyboard, I want to use the virtual keypad instead to enter the numbers (technically, a String). Any suggestions?

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

public class EmbeddedMain extends JFrame
{

    public static void main (String[] args)
        {
        EmbeddedMain em = new EmbeddedMain();
        }


    public EmbeddedMain()
    {
        setTitle("testing");
        setSize(450,350);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new GridLayout(4,5,3,3));

    JButton button1= new JButton("7");
    JButton button2= new JButton("8");
    JButton button3= new JButton("9");
    JButton button4= new JButton("4");
    JButton button5= new JButton("5");
    JButton button6= new JButton("6");
    JButton button7= new JButton("1");
    JButton button8= new JButton("2");
    JButton button9= new JButton("3");
    JButton button0= new JButton("0");
    JButton buttonR= new JButton("Reset");
    JButton buttonE= new JButton("Enter");

     JTextField x = new JTextField("      ");
     JTextField y = new JTextField("      ");
     JTextField CPP_entry = new JTextField("    ");

   CPP_entry.setEditable(false);        

    add(button1);
    add(button2);
    add(button3);
    add(new JLabel("    x:")); 
    add(x); 
    add(button4);
    add(button5);
    add(button6);
    add(new JLabel("    y:")); 
    add(y); 
    add(button7);
    add(button8);
    add(button9);
    add(new JLabel("    x-y:")); 
    add(CPP_entry); 
    add(buttonR);
    add(button0);
    add(buttonE);

        setVisible(true);


        }

        }

Answer

deorst picture deorst · Nov 9, 2010

I'd make an array of buttons like this:

JButton[] buttonArray = new JButton[10];
for(int i = 0; i < buttonArray.length; i++ ) {
  buttonArray[i] = new JButton(String.valueOf(i));
  buttonArray[i].addActionListener(yourActionListener);
}

and then when the event fires check for its origin.