OMG-1
OMG-1

Reputation: 508

Rounded corner on JTextField and make it consistent through different PLAFs

Hello dear fellow stackoverflow users,

I got a simple hack where I get my long wanted round corners on a JTextField.
I found that I could subclass JTextField and override paintComponent(Graphics g)

In that regard I could edit the following:

Now I'm battling with the following issues:

So in very short, does any of you know how I dissect the JTextField with the various issues, written above?

Written is my sample code for making rounded borders in a custom class JTextField within the constructor setBorder(BorderFactory.createEmptyBorder()) and setOpaque(false);:

@Override
public Insets getInsets() {
    Insets insets = super.getInsets();
    insets.left += 10;
    return insets;
}

@Override
public Insets getInsets(Insets insets) {
    return insets;
}

@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = Graphics2D)g.create();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    RoundRectangle2D.Float r2d = new RoundRectangle2D.Float(0, 0, getWidth(), getHeight(), 10, 10);
    Paint backgroundBrush = new GradientPaint(0, 0, new Color(0x383838), 0, getHeight(), new Color(0xCECECE).darker());
    Shape oldClip = g2.getClip();
    g2.setPaint(backgroundBrush);
    g2.clip(r2d);
    g2.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
    g2.setClip(oldClip);
    g2.setColor(Color.black);
    g2.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 10, 10);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    g2.dispose();
    super.paintComponent(g);
}

Upvotes: 1

Views: 2422

Answers (2)

Alan Hunt
Alan Hunt

Reputation: 1

I was having the same issue, and found that calling

setBackground(new Color(0,0,0,0))

on the text field class cleared it up. I think that it is not making the background non opaque even if you declare the widget non opaque.

Upvotes: 0

camickr
camickr

Reputation: 324128

I would think you should be creating a custom Border for this. Then you can control the insets and do the painting in the Border, instead of the paintComponent() method of the text field.

Upvotes: 2

Related Questions