Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

JTextField – Font, Color & Alignment

1. JTextField Introduction

JTextField component will render an Edit control, which will take user input. We can construct it by passing an integer as a parameter and the integer specify the char-width. For example, if we pass a value of 15, Java Swing will create a text field to show 15 letters. We can change the colour of the JTextField by calling its setForground method. The setFont method is useful for setting a font to the JTextField.

2. About the JTextField Example

Have a look at the example below:

Java Swing - JTextField Example
Java Swing – JTextField Example

The example shows three JTextFields. Each text fields contains the text in different text colour. Also, we may notice that the texts alignments are different. First JTextField shows the text left aligned. The second control shows the text aligned towards the middle of the text field. Final text field shows the text right aligned. You may also notice we display all texts in a bigger size than the default.

3. Create JTextFields

The below code shows that first we create flow layout for the JFrame. Then we create three JTextFields for our example. In all three instances, we specified a value of 30. This tells Java Swing the size of the text field in terms of Character Width and swing calculates the size in pixels. So, all our text boxes can show thirty letters.

The add method on the content pane will add all three text boxes to the JFrame Window. Note, the order is important and Swing container displays the components in the order in which it was added to it.

The method setText will set the text for the JTextFields. In the below code, we set three different texts for the JTextFields.

4. Set Font & Color for JTextField

In the code snippet below at line number 2, we create an AWT Font. The first param is the font name, 2nd one is the font style and third param tells the size of the Font. In our example, we create Plain font style. One can try other styles also like bold & italic. Then, using the setFont method, the Font is set to the JTextField. The method setForeGround will take AWT color object and sets that to the component. Here the component is JTextField.

5. JTextField Text Alignment

The function setHorizontalAlignment will decide where to place the text. Mean towards the left or right or in the middle. To study how it works, we set three different alignments for our three sample Java Swing JTextFields. Note how we pass the constants to the function setHorizontalAlignment method call.

6. Watch JTextField as Youtube Video

7. Code Reference

Categories: Swing

Tags: , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.