• Post Reply Bookmark Topic Watch Topic
  • New Topic

JButton and getting multiple inputs  RSS feed

 
Mozahid Haque
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys,

I have created a simple set of buttons involving numbers 0 to 9.
I would like to get 4 numbers from these buttons, say if a person
clicked 1 2 3 4. I would like to have gotten those 4 or, in general, any
number of singular clicks of those buttons. Do you know of any
way to do this?

I was thinking I have an external string and storing singular clicks
into the string and then stopping at 4 somehow, but I really have no
idea how.

Thanks for any help.
 
A Jay Smith
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also a beginner here so beware any advice. However -
Isn't setActionCommand + getActionCommand what you are looking for?
Set a different command for each button so that it stores a number to an array and counts the clicks with NumberOfClicksOfButtons++. Use this to insert the number into the right spot in the array. Also use the number of clicks to stop inserting numbers or you'll get an array out of bounds exception (I take it you only want 4 numbers from what you are saying? If you need more than a set amount an array wont do you need a list).
If you need a string again from the array use Arrays.toString(yourArray)
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome, both of you

You need to start thinking object-oriented. This is a prime candidate for a class to be written for. You can write a NumberActionListener, or a NumberAction. You can create an array of ten buttons, each linked to a number-something object. (Or eleven buttons, the 11th having “.” as its output value.)
You can create a whole keyboard if you create enough buttons (I think 104 for a full-size keyboard).
You need to work out how to collect the inputs into a String, or a number. One possible way to collect the numbers would be to pass an instance of StringBuilder to all their constructors; clicking each button appends a character to that Builder. Clicking a button like +−×÷ both takes the output for use in your arithmetic, and clears the builder. The easiest way to clear a StringBuilder is probably to set its length to 0. Your listener/action for “.” might have an alreadyUsed field or a test whether the builder already contains the decimal point, and can throw an Exception if you try to use it twice.
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can easily interrogate a StringBuilder for its length. If you are setting a maximumLength field, that is best set via the constructor; that way you can permit 5-digit numbers instead.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!