JTextField là một lớp con của JTextComponent và là thành phần quan trọng cho phép nhập văn bản một dòng (single-line). JTextField tạo ActionListener khi nhập input. Các phương thức quan trọng: setText(), getText(), setEnabled() v.v. Mặc định JTextField hình chữ nhật, chúng ta có thể triển khai JTextField bo tròn bằng lớp RoundRectangle2D và ghi đè paintComponent().
Ví dụ
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class RoundedJTextFieldTest extends JFrame {
private JTextField tf;
public RoundedJTextFieldTest() {
setTitle("RoundedJTextField Test");
setLayout(new BorderLayout());
tf = new RoundedJTextField(15);
add(tf, BorderLayout.NORTH);
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new RoundedJTextFieldTest();
}
}
// Triển khai JTextField bo tròn
class RoundedJTextField extends JTextField {
private Shape shape;
public RoundedJTextField(int size) {
super(size);
setOpaque(false);
}
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new RoundRectangle2D.Float(0, 0, getWidth() - 1, getHeight() - 1, 15, 15);
}
return shape.contains(x, y);
}
}
Kết quả
