Reputation: 1132
I wrote a short program because I wanted to create a custom-made button with rounded corners. Therefore I extended the JButton class and overwrote the paintComponent method (see code below).
public class JRoundedButton extends JButton {
private int arcRadius;
public JRoundedButton(String label, int arcRadius) {
super(label);
this.setContentAreaFilled(false);
this.arcRadius = arcRadius;
}
@Override
protected void paintComponent(Graphics g) {
if(g instanceof Graphics2D) {
Graphics2D graphics = (Graphics2D) g;
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//Draw button background
graphics.setColor(getBackground());
graphics.fillRoundRect(getX(), getY(), getWidth() - 1, getHeight() - 1, arcRadius, arcRadius);
}
}
@Override
public boolean contains(int x, int y) {
return new RoundRectangle2D.Double(getX(), getY(), getWidth(), getHeight(), arcRadius, arcRadius).contains(x,y);
}
public int getArcRadius() {
return arcRadius;
}
public void setArcRadius(int arcRadius) {
this.arcRadius = arcRadius;
this.repaint();
}
}
When I create a simple frame and add ONE button to a panel, that I then add to the frame it shows up perfectly. But as soon as I want to create two buttons and set them below each other (having Borderlayout I used NORTH and SOUTH) only the upper button shows up correct. The button below displays the text correctly (I removed that part from the painComponent(...) method), but the background isn't painted. I do not use the setOpaque(...) method in any way.
What could the problem be?
Do I need to set the bounds of my custom button?
Edit: Here is the code that creates the frame and displays the buttons:
public static void main(String[] args) {
JFrame frame = new JFrame("Buttontest");
frame.setSize(new Dimension(500, 500));
frame.setLayout(new BorderLayout());
JPanel contentPanel = new JPanel();
contentPanel.setSize(new Dimension(500, 500));
contentPanel.setLayout(new GridLayout(2, 1, 0, 20));
JRoundedButton button1 = new JRoundedButton("Rounded Button", 40);
button1.setForeground(Color.YELLOW);
button1.setBackground(Color.GREEN);
JRoundedButton button2 = new JRoundedButton("Rounded Button 2", 40);
button2.setBackground(Color.BLACK);
button2.setForeground(Color.WHITE);
contentPanel.add(button1);
contentPanel.add(button2);
frame.add(contentPanel, BorderLayout.CENTER);
frame.setVisible(true);
}
The output is this:
Why is the background of the lower button not visible? It should be black!
Upvotes: 1
Views: 57
Reputation: 26
in your paintComponent()
you need fillRoundRect(0,0,...)
instead of getX()
and getY()
because g is relative to the component itself.
Upvotes: 1