I wanted to paint my own version of JButton, so I have overridden the paintComponent()
method, and drew a gradient roundRect. This works, but after that, I want to draw the String of the Button over it, and at compile-time, I got no error messages. But at runtime, I only see the roundRect, gradient, just as I intended it to be (I can click on it too), but the String is invisible...
Here's my code:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
public class JIconButton extends JButton implements MouseListener
{
private boolean mouseInside;
public JIconButton(String file, String text)
{
super(text, new ImageIcon(file));
setBorder(new LineBorder(Color.LIGHT_GRAY, 0, true));
setContentAreaFilled(false);
setFocusPainted(false);
addMouseListener(this);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
@Override
protected void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g.create();
g2.setPaint(Color.BLACK);
g2.drawString(getText(), 0, 0);
g2.setPaint(new GradientPaint(
new Point(0, 0),
Color.WHITE,
new Point(0, getHeight()),
Color.PINK.darker()));
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 30, 30);
g2.dispose();
//super.paintComponent(g);
}
}
You have to do:
the
y
of the string coordinate must be greater than0
, because is the starting point of the baseline and not the point of the upper left corner of a box. The final code:1) easiest way would be JButton's methods JButton(String text, Icon icon) example here
2) you can override XxxButtonUI, or change GradientButton
As per my comment, "it worked for me...."
For example: