How to Input Dialogs in Java Swing
Swing is the Java programming language's standard library for building complete graphical user interfaces for Java programs, including textual input fields. Depending on the way you prefer to design your interfaces, you might prefer to write out directions for what your program's user should type into each field with dialogue text that your program initially writes into each respective field. You can set this text when you first create these objects, or reset the text later in your program.
Instructions
-
-
1
Add the line "import javax.swing.JTextField;" to the top of your source code to make sure that Java reads in the necessary libraries for Swing to work.
-
2
Create your Input fields and dialogue with the syntax "JTextField myTextField = new JTextField("My Dialogue");" where "myInput" is the name you want to give your text field object and "My Dialogue" is the dialogue text you want to initially display in the text field. If you want a larger text input area than a single line, use the syntax "JTextArea myInput = new JTextArea("My Dialogue", x, y);" where "x" and "y" are the length and width, respectively, you want the input field to occupy.
-
-
3
Use the syntax "myInput.setText("New Dialogue Text");" to reset whatever text is currently in the input area, be it your text or text the application user has typed in, to "New Dialogue Text" later in the program.
-
1
References
- Oracle: Class JTextArea
- Oracle: Class JTextField
- Core Java Volume I: Fundamentals; Cay S. Horstmann and Gary Cornell
- Photo Credit Comstock/Comstock/Getty Images