[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

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).

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.

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