एक JTextField, JTextComponent क्लास का एक सबक्लास है और यह सबसे महत्वपूर्ण कंपोनेंट्स में से एक है जो यूजर को सिंगल-लाइन फॉर्मेट में इनपुट टेक्स्ट मान दर्ज करने की अनुमति देता है। जब हम इसके अंदर कुछ इनपुट दर्ज करने का प्रयास करते हैं तो JTextField क्लास ActionListener इंटरफेस उत्पन्न करेगी। JTextField क्लास के महत्वपूर्ण मेथड्स हैं: setText(), getText(), setEnabled() आदि। डिफ़ॉल्ट रूप से, एक JTextfield का आयताकार आकार होता है, हम RoundRectangle2D क्लास का उपयोग करके और paintComponent() मेथड को ओवरराइड करके गोलाकार JTextField भी इम्प्लीमेंट कर सकते हैं।
उदाहरण
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);
}
}
आउटपुट
