1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| public class ButtonBorder implements Border {
private final int margins;
private final Color color;
private final int thickness;
private boolean active;
public ButtonBorder(Color color, int margins, int thickness) {
Objects.requireNonNull(color);
this.margins=Math.max(margins,0);
this.color=color;
this.thickness=Math.min(Math.max(thickness,0),this.margins);
}
protected void setActive(boolean active) {
this.active=active;
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
if( active ) {
g.setColor(color);
g.fillRect(x, y+height-thickness, width, thickness);
}
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(margins, margins, margins, margins);
}
@Override
public boolean isBorderOpaque() {
return false;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Démo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridBagLayout());
frame.add(createJButton());
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static Component createJButton() {
final JButton button = new JButton("Fermer");
final ButtonBorder border = new ButtonBorder(Color.RED, 5, 2);
button.setBorder(border);
button.setBackground(Color.BLACK);
button.setForeground(Color.WHITE);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
border.setActive(true);
button.repaint();
}
@Override
public void mouseExited(MouseEvent e) {
border.setActive(false);
button.repaint();
}
});
return button;
}
} |
Partager