Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

button press -> +1  RSS feed

 
Linus Brutus
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a frame with a number in it, I want that whenever the user presses <space> the number goes +1
 
Campbell Ritchie
Marshal
Posts: 55795
164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like a candidate for transfer to the Swing forum.

Maybe, just maybe . . .
  • Either: Extend the JButton class to have a number as a field,
  • Or: Create a class with a JButton and a number as its fields.
  • Add an ActionListener to the button.
  • The ActionListener does two things: 1: myNumber++;
  • 2: myButton.setText("" + myNumber);
  •  
    Linus Brutus
    Greenhorn
    Posts: 2
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Think something was misunderstood, I don't see any need for a Jbutton. I just want to change the value of a variable when a key on the keyboard is pressed.

    I was thinking that key bindings would be the answer but I can't seem to understand what it does and I can't find a code that contains what I need.
     
    Campbell Ritchie
    Marshal
    Posts: 55795
    164
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Oh, sorry, I misread your post.

    Try a KeyListener and use the KeyEvent object to get the key pressed. There is a long list of possible keys; I think you want VK_SPACE. Then use the actions I told you about earlier.
     
    Campbell Ritchie
    Marshal
    Posts: 55795
    164
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You did actually entitle the thread "button press." That is why I was mistaken.
     
    Michael Dunn
    Ranch Hand
    Posts: 4632
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    > I was thinking that key bindings would be the answer

    It is.


    > but I can't seem to understand what it does and I can't find a code that contains what I need.

    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
     
    Campbell Ritchie
    Marshal
    Posts: 55795
    164
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    After a half-second look at the Java Tutorial link you posted, that seems quite straightforward.
     
    Consider Paul's rocket mass heater.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!