A JTextField เป็นคลาสย่อยของ JTextComponent และเป็นหนึ่งในองค์ประกอบที่สำคัญที่สุดที่อนุญาตให้ผู้ใช้ป้อนค่าข้อความในรูปแบบรูปแบบบรรทัดเดียว . คลาส JTextField จะสร้าง ActionListener อินเทอร์เฟซเมื่อเราพยายามป้อนอินพุตภายใน วิธีการที่สำคัญของคลาส JTextField คือ setText(), getText(), setEnabled() และอื่นๆ ตามค่าเริ่มต้น JTextfield จะมีรูปทรงสี่เหลี่ยมผืนผ้า เรายังสามารถใช้ รูปทรงกลม JTextField โดยใช้ Rectangle2D คลาสและจำเป็นต้องแทนที่ paintComponent() วิธีการ
ตัวอย่าง
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();
}
}
// implement a round-shaped JTextField
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);
}
} ผลลัพธ์
