Reputation: 11493
I overrided the paint component of a JButton, but now when I click it doesn't get darker. I searched google and stack overflow, but there doesn't seem to be an answer. So how do I make the button get darker when I click down and then return to normal when I finish the click?
Here is my code:
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
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),
BUTTON_TOP_GRADIENT,
new Point(0, getHeight()),
BUTTON_BOTTOM_GRADIENT));
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
g2.dispose();
}
Upvotes: 1
Views: 204
Reputation: 67360
This code snippet at the bottom works for me. Here's how it works:
I check the button's model to see if the button is clicked. When it is clicked, it paints itself differently.
package com.sandbox;
import javax.swing.*;
import java.awt.*;
public class SwingSandbox {
public static void main(String[] args) {
JFrame frame = buildFrame();
frame.add(new MyButton());
}
private static class MyButton extends JButton {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Color color;
if (getModel().isPressed()) {
color = new Color(0, 0, 0);
} else {
color = new Color(0, 0, 255);
}
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),
color,
new Point(0, getHeight()),
new Color(255, 255, 0)));
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
g2.dispose();
}
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
Upvotes: 3