How can we implement a rounded JTextField in Java?

A JTextField is a subclass of JTextComponent class and it is one of the most important components that allow the user to an input text value in a single-line format. A JTextField class will generate an ActionListener interface when we trying to enter some input inside it. The important methods of a JTextField class are setText(), getText(), setEnabled() and etc. By default, a JTextfield has a rectangle shape, we can also implement a round-shaped JTextField by using the RoundRectangle2D class and need to override the paintComponent() method.


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);
   public static void main(String args[]) {
      new RoundedJTextFieldTest();
// implement a round-shaped JTextField
class RoundedJTextField extends JTextField {
   private Shape shape;
   public RoundedJTextField(int size) {
protected void paintComponent(Graphics g) {
   g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
protected void paintBorder(Graphics g) {
   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);


Updated on: 10-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started