Je suis en train de développer un nouveau look and feel pour swing et j'ai un problème lorsque je crée une ombre dans le JComponent. Par exemple, lorsque je crée un JButton avec une couleur différente du blanc, l'effet de l'ombre n'est pas correct.
C'est le code comme la création de l'ombre.
protected void paintShadow(@NotNull Graphics g, @NotNull JComponent c){
int shade = 0;
int topOpacity = 80;
int pixels = UIManager.getInt("Button[Default].shadowPixel");
JButton b = (JButton) c;
for (int i = 0; i < pixels; i++) {
g.setColor(new Color(shade, shade, shade, ((topOpacity / pixels) * i)));
g.drawRoundRect(i, i, b.getWidth() - ((i * 2) + 1), b.getHeight() - ((i * 2) + 1), 7, 7);
}
}
et voici le bon effet avec la couleur blanche
et voici le mauvais effet avec l'autre couleur.
Comment puis-je généraliser ma méthode paint shadow ?
Voici un exemple minimal pour ce code
import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
/**
* @author https://github.com/vincenzopalazzo
*/
public class MaterialMain extends JFrame {
static {
UIManager.put("Button[Default].shadowPixel", 3);
}
public void init() {
JPanel panel = new JPanel();
JButton witheRightEffect = new JButton("shadow withe");
witheRightEffect.setUI(new ShadowButtonUI());
JButton otherColorWrongEffect = new JButton("shadow other color");
otherColorWrongEffect.setBackground(Color.GREEN);
otherColorWrongEffect.setUI(new ShadowButtonUI());
panel.add(witheRightEffect);
panel.add(otherColorWrongEffect);
setTitle("Look and feel");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(630, 360);
add(panel);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MaterialMain main = new MaterialMain();
main.init();
}
});
}
public class ShadowButtonUI extends BasicButtonUI{
@Override
public void installUI(JComponent c) {
super.installUI(c);
c.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
paintShadow(g, c);
}
protected void paintShadow( Graphics g, JComponent c){
int shade = 0;
int topOpacity = 80;
int pixels = UIManager.getInt("Button[Default].shadowPixel");
JButton b = (JButton) c;
for (int i = 0; i < pixels; i++) {
g.setColor(new Color(shade, shade, shade, ((topOpacity / pixels) * i)));
g.drawRoundRect(i, i, b.getWidth() - ((i * 2) + 1), b.getHeight() - ((i * 2) + 1), 7, 7);
}
}
}
}
Le bouton blanc a un effet correct, mais l'ombre du bouton vert est fausse.