sinθ
sinθ

Reputation: 11493

How to draw the label onto a custom JButton?

I extended the JButton class to make my own custom version, but now I don't know how to make the JLabel appear over it. In a normal button, the JLabel is painted on top of it, but I don't know how to replicate that behavior. Any idea how?

This is the paintComponent method that I overrode:

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    boolean isSelected = getModel().isPressed();
    Color topColor =  !isSelected ? BUTTON_TOP_GRADIENT : BUTTON_TOP_GRADIENT.darker();
    Color bottomColor =  !isSelected ? BUTTON_BOTTOM_GRADIENT : BUTTON_BOTTOM_GRADIENT.darker();

    Graphics2D g2 = (Graphics2D)g.create();
    RenderingHints qualityHints =
            new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHints(qualityHints);
    g2.setPaint(new GradientPaint(
            new Point(0, 0), 
            topColor, 
            new Point(0, getHeight()), 
            bottomColor));
    g2.fillRoundRect(0, 0, getWidth(), getHeight(), BUTTON_CORNER_RADIUS, BUTTON_CORNER_RADIUS);
    g2.setColor(Color.BLACK);
    g2.dispose();

    // Where I need to draw the JLabel


}

Upvotes: 0

Views: 145

Answers (2)

camickr
camickr

Reputation: 324147

The paintComponent() method is responsible for painting the background, text and icon. You call this code and then paint on top of everything with your custom code. So you lose all the default painting of the text and icon.

You need to invoke the paintComponent() method at the bottom of your code. In the constructor of your class you would also need to add:

setContentAreaFilled( false );

This will prevent the paintComponent() method from repainting the background again.

Upvotes: 2

Pavel Ryzhov
Pavel Ryzhov

Reputation: 5162

Instead of drawing label you can use drawString method of Graphics2D. Something like:

g2.drawString("Label text", 10, 40);

Upvotes: 0

Related Questions