• Post Reply Bookmark Topic Watch Topic
  • New Topic

Get numerical value from JTextField on focus

 
Mohammad Ashari Rahman
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi. I want to get the value from user when user clicks JTextField and enters a value. But it is giving me illegalnumberformatexception

 
Vaibhav Sagar
Ranch Hand
Posts: 35
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, could you tell what value are you getting for "txtAddRooms.getText()"-

 
Fred Kleinschmidt
Bartender
Posts: 454
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to get the value from user when user clicks JTextField and enters a value.

If you use a FocusListener, it gets called as soon as the user clicks on the text field- before the user has a chance to type anything! So if the field is empty when the user clicks on it, your code tries to convert that to a number, and an empty string will produce a NumberFormatException.
You should use an ActionListener or DocumentListener instead.
 
Rob Camick
Ranch Hand
Posts: 2699
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


But you set the text as "Add Rooms", which obviously is not a number.

Typically you might have two components:

1) JLabel addRoomsLabel = new JLabel("Add Rooms");
2) JTextField addRoomsText = new JTextField("0");

Then you might have a JButtton:

3) JButton process = new JButton("Process");

then when the use clicks the button you convert the text of the text field to a number and do your processing.

Or maybe you don't event use a JTextField. Maybe you use a JComboBox that contains values 0, 1, 2, 3, etc.

Can't really give advice because we don't know what you are trying to do.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!