javaswingjbuttonnumeric-keypad

How to do a number keypad in java


I trying to figure out how to do a number keypad in java. I'm recently started using java, still have so much to learn. The following is what I came up with so far but it only returns one char at a time. Still researching this, but would really appreciate any assistance..thanks

currentButton = (JButton)event.getSource();
itemQuantity = currentButton.getText().charAt(0) - '0';

Solution

  • It looks like you're using the button's text as the value of one digit in a number representing itemQuantity. Each time a button is pressed, you should append that button's digit to a string:

    String currentString = "";
    currentString += currentButton.getText();
    

    Then you can get the numeric value as @user1804740 suggests:

    itemQuantity = Integer.parseInt(currentString);
    

    Note, you'll have to handle any NumberFormatException thrown by the conversion.