Showing posts with label JTextField. Show all posts
Showing posts with label JTextField. Show all posts

Tuesday, August 10, 2010

Setting Initial value for InputDialog in JOptionPane

There are 6 showInputDialog methods in JOptionPane class and we can select either one of these methods based on our requirements. To create an initial value when an InputDialog pops out we need to make use of method with these signatures:
public static Object showInputDialog(Component parentComponent,
Object message,
String title,
int messageType,
Icon icon,
Object[] selectionValues,
Object initialSelectionValue)
throws HeadlessException
Let me describe the parameters in a more understandable way compared to the ones in the Java API Doc.
  • parentComponent - the parent Component for the dialog
  • message – The message to display when the dialog pops out
  • title – The title of the dialog
  • messageType - the type of message to be displayed: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE
  • icon – Your very own icon for the dialog
  • selectionValues – Provide few values to select (If this is null, the input field will be a JTextField rather than a JComboBox)
  • initialSelectionValue – The default initial value for the dialog


If you look at the code above, I made the parentComponent as null because the dialog is not referring to any component and I’ve declared the icon null as well because I don’t need a customized icon.

When I declare the selectionValues with an array called values, the input field turns into a JComboBox and the default value is assigned based on the initialSelectionValue, in this case its "A".

Let's say I don't want to provide options to the users and expect them to key in the values manually, but I still want to provide an initial value. All I have to do for that is, make the selectionValues parameter as null.


For further reference, have a look at the javadoc for JOptionPane: JOptionPane

Author: Thiagu

Wednesday, April 28, 2010

Perform an Event when “Enter” key is pressed

For this month since I had very limited time to come up with a post, I thought of discussing about this common yet simple question that many newbie have in mind.

Let’s say I have a JTextField and a JTextArea and every time when I press the “ENTER” key on the JTextfield, I need to append the text from the JTextField to the JTextArea.

This is a very simple scenario and to accomplish this we have to make use of the “KeyAdapter Class (which implements the KeyListener Interface)” and “KeyEvent Class”.

Once the key “Enter” is pressed we need to perform the action, so at this point we need to make use of the “keyReleased(KeyEvent evt)” method from the adapter class and then check if the keycode is equals to “evt.VK_ENTER”. The code snippets are as below.

For further reference and study kindly refer to this link http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html

Author: Thiagu