| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package com.bulenkov.iconloader.util; |
| 18 |
|
| 19 |
import javax.swing.*; |
| 20 |
import java.awt.*; |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
public class CenteredIcon implements Icon { |
| 26 |
private final Icon myIcon; |
| 27 |
|
| 28 |
private final int myWidth; |
| 29 |
private final int myHight; |
| 30 |
|
| 31 |
private final boolean myCenteredInComponent; |
| 32 |
|
| 33 |
public CenteredIcon(Icon icon) { |
| 34 |
this(icon, icon.getIconWidth(), icon.getIconHeight(), true); |
| 35 |
} |
| 36 |
|
| 37 |
public CenteredIcon(Icon icon, int width, int height) { |
| 38 |
this(icon, width, height, true); |
| 39 |
} |
| 40 |
|
| 41 |
public CenteredIcon(Icon icon, int width, int height, boolean centeredInComponent) { |
| 42 |
myIcon = icon; |
| 43 |
myWidth = width; |
| 44 |
myHight = height; |
| 45 |
myCenteredInComponent = centeredInComponent; |
| 46 |
} |
| 47 |
|
| 48 |
@Override |
| 49 |
public void paintIcon(Component c, Graphics g, int x, int y) { |
| 50 |
int offsetX; |
| 51 |
int offsetY; |
| 52 |
|
| 53 |
if (myCenteredInComponent) { |
| 54 |
final Dimension size = c.getSize(); |
| 55 |
offsetX = size.width / 2 - myIcon.getIconWidth() / 2; |
| 56 |
offsetY = size.height / 2 - myIcon.getIconHeight() / 2; |
| 57 |
} else { |
| 58 |
offsetX = (myWidth - myIcon.getIconWidth()) / 2; |
| 59 |
offsetY = (myHight - myIcon.getIconHeight()) / 2; |
| 60 |
} |
| 61 |
|
| 62 |
myIcon.paintIcon(c, g, x + offsetX, y + offsetY); |
| 63 |
} |
| 64 |
|
| 65 |
@Override |
| 66 |
public int getIconWidth() { |
| 67 |
return myWidth; |
| 68 |
} |
| 69 |
|
| 70 |
@Override |
| 71 |
public int getIconHeight() { |
| 72 |
return myHight; |
| 73 |
} |
| 74 |
} |