[JavaSwing] JTextField

Content
Create simple JTextField
Taken, data set from JTextField
Align and start the event for JTextField
Some other methods

JTextField is an object that allows the user to enter a line of text. Often used to enter data with brief information.
JTextField
In the illustration above we have 4 JTextField to allow users to enter 4 corresponding information 4 JLabel on the left.

Example 1: Create simple JTextField

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package nguyenvanquan7826.JTextField;
 
import java.awt.GridLayout;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
 
public class MyJTextField extends JFrame {
    public MyJTextField() {
        // create JFrame
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2, 1, 5, 5));
 
        // create and add JTextField
        JTextField tf = new JTextField(20);
        add(tf);
 
        // add a JButton
        add(new JButton("Ok"));
 
        // Display JFrame
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
 
    public static void main(String[] args) {
        new MyJTextField();
    }
}

create JtextField
The constructor JTextField
– JTextField(): Create new 1 JTextField
JTextField(Document doc, String text, int columns): Create 1 JTextField using text storage model with text and columns (coloumns)
JTextField(int columns): Create JTextField width is empty columns
JTextField(String text): Create a JTextField with the previous text
JTextField(String text, int columns): Create JTextField with a given text and width.

Example 2: Taken, placed and processed data from JTextField

In this example we will do 1 small demo like opening image of all, further 1 JButton to re-enter data – A demo for interest calculation (No notification if the data is wrong but will jump to JTextField if it does not have data).

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
package nguyenvanquan7826.JTextField;
 
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class TienLai extends JFrame implements ActionListener {
    private JTextField tfTienGui, tfLaiXuat, tfThang, tfTienLai;
 
    public TienLai() {
        // ------------ create JFrame ------------ //
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(5, 2, 5, 5));
 
        // ------------ add content ------------ //
 
        int size = 15;
        add(new JLabel("Tiền gửi"));
        tfTienGui = new JTextField(size);
        add(tfTienGui);
 
        add(new JLabel("Lãi xuất / Tháng"));
        tfLaiXuat = new JTextField(size);
        add(tfLaiXuat);
 
        add(new JLabel("Tháng"));
        tfThang = new JTextField(size);
        add(tfThang);
 
        add(new JLabel("Tiền lãi"));
        tfTienLai = new JTextField(size);
        tfTienLai.setEditable(false);// khong cho phep nhap du lieu
        add(tfTienLai);
 
        add(createJButton("Tính"));
        add(createJButton("Nhập lại"));
 
        // ------------ display ------------
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
 
    private JButton createJButton(String buttonName) {
        JButton btn = new JButton(buttonName);
        btn.addActionListener(this);
        return btn;
    }
 
    public static void main(String[] args) {
        new TienLai();
    }
 
    private void process() {
        // check data
        String text = tfTienGui.getText();
        double tienGui = 0, tienLai = 0, thang = 0, laiXuat = 0;
 
        // tien gui
        if (text.equals("")) {
            tfTienGui.requestFocus(); // nhay den de nhap tien gui
        } else {
            tienGui = Double.parseDouble(text);
 
            // lai xuat
            text = tfLaiXuat.getText();
            if (text.equals("")) {
                tfLaiXuat.requestFocus(); // nhay den de nhap lai xuat
            } else {
                laiXuat = Double.parseDouble(text);
 
                // thang
                text = tfThang.getText();
                if (text.equals("")) {
                    tfThang.requestFocus(); // nhay den de nhap thang
                } else {
                    thang = Integer.parseInt(tfThang.getText());
                }
            }
        }
 
        // process data
        double lai = tienGui * laiXuat * thang;
        tfTienLai.setText(String.valueOf(lai)); // hien thi ket qua
    }
 
    private void clear() {
        tfTienGui.setText("");
        tfTienGui.requestFocus(); // nhay ve de nha tien gui
        tfLaiXuat.setText("");
        tfThang.setText("");
        tfTienLai.setText("");
    }
 
    // methods of ActionListener
    @Override
    public void actionPerformed(ActionEvent evt) {
        String command = evt.getActionCommand();
        if (command == "Tính") {
            process();
        }
        if (command == "Nhập lại") {
            clear();
        }
    }
}

get data of JTextField
The remarkable thing
Want to get the data (that there is actually a string) we use methods from JTextField getText().
Want to put data the methods we use JTextField setText(String text).
Method requestFocus() Help cursor jumps (concentrate) to this JTextField.
Method setEditable(boolean edit) to have been imported data set for JTextField or not.

Example 3: Aligning and create events for JTextField

In this example we will create 1 JTextFiel that when they enter our text is right-aligned (The default is left margin), when you press enter, it will display the data entered on 1 JLabel.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package nguyenvanquan7826.JTextField;
 
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
 
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
 
public class AlignAndAction extends JFrame implements KeyListener {
 
    private JTextField tf;
    private JLabel lb;
 
    public AlignAndAction() {
        createJFrame();
        addContent();
        displayJFrame();
    }
 
    // create JFrame
    private void createJFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(2, 1, 5, 5));
    }
 
    // display JFrame
    private void displayJFrame() {
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
 
    private void addContent() {
        tf = new JTextField(20);
        tf.setHorizontalAlignment(JTextField.RIGHT);// can trai
        tf.addKeyListener(this);
        add(tf);
 
        lb = new JLabel("Not data");
        add(lb);
    }
 
    private void updateData() {
        lb.setText(tf.getText());
    }
 
    public static void main(String[] args) {
        new AlignAndAction();
    }
 
    @Override
    public void keyPressed(KeyEvent e) {// nhan vao phim
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            updateData();
        }
    }
 
    @Override
    public void keyReleased(KeyEvent e) { // nha phim ra
    }
 
    @Override
    public void keyTyped(KeyEvent e) { // nhap 1 phim
    }
}

catch events JTextField
Like JButton, JTextField also capture mouse events, and even the keys on the keyboard again. To capture the key events of the methods we use addKeyListener() and similar capturing events JButton but with KeyListener not with ActionListener.
Using methods setHorizontalAlignment to align the JTextField.

Some other methods

getSelectedText(): get selected text in JTextField
setSelectionStart(int selectionStart) and setSelectionEnd(int selectionEnd) set the start position and end to selected text. If no method setSelectionStart the text will be selected from the current position of the cursor (Smaller selectionEnd) to selectionEnd. If no method setSelectionEnd the text will be selected from location to location selectionStart current cursor (greater selectionStart).
getCaretPosition() and setCaretPosition(position) get and set the current position of the cursor.

Refer to: class JTextField, Use JTextField