Code
private static JComponent makeCompoundButton(final Dimension d) {
JPanel p = new JPanel() {
@Override public Dimension getPreferredSize() {
return d;
}
};
p.setLayout(new OverlayLayout(p));
p.add(new CompoundButton(d, ButtonLocation.NOTH));
p.add(new CompoundButton(d, ButtonLocation.SOUTH));
p.add(new CompoundButton(d, ButtonLocation.EAST));
p.add(new CompoundButton(d, ButtonLocation.WEST));
p.add(new CompoundButton(d, ButtonLocation.CENTER));
return p;
}
class CompoundButton extends JButton {
protected final Color fc = new Color(100,150,255,200);
protected final Color ac = new Color(230,230,230);
protected final Color rc = Color.ORANGE;
protected Shape shape;
protected Shape base = null;
private final ButtonLocation bl;
private final Dimension dim;
public CompoundButton(Dimension d, ButtonLocation bl) {
super();
this.dim = d;
this.bl = bl;
setIcon(new Icon() {
@Override public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D)g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(getModel().isArmed()) {
g2.setColor(ac);
g2.fill(shape);
}else if(isRolloverEnabled() && getModel().isRollover()) {
paintFocusAndRollover(g2, rc);
}else if(hasFocus()) {
paintFocusAndRollover(g2, fc);
}else{
g2.setColor(getBackground());
g2.fill(shape);
}
g2.dispose();
}
@Override public int getIconWidth() {
return dim.width;
}
@Override public int getIconHeight() {
return dim.height;
}
});
setFocusPainted(false);
setContentAreaFilled(false);
setBackground(new Color(250, 250, 250));
initShape();
}
@Override public Dimension getPreferredSize() {
return dim;
}
protected void initShape() {
if(!getBounds().equals(base)) {
base = getBounds();
float ww = getWidth() * 0.5f;
float xx = ww * 0.5f;
Shape inner = new Ellipse2D.Float(xx, xx, ww, ww);
if(ButtonLocation.CENTER==bl) {
shape = inner;
}else{
Shape outer = new Arc2D.Float(
1, 1, getWidth()-2, getHeight()-2,
bl.getStartDegree(), 90f, Arc2D.PIE);
Area area = new Area(outer);
area.subtract(new Area(inner));
shape = area;
}
}
}
private void paintFocusAndRollover(Graphics2D g2, Color color) {
g2.setPaint(new GradientPaint(0, 0, color,
getWidth()-1, getHeight()-1, color.brighter(), true));
g2.fill(shape);
g2.setColor(getBackground());
}
@Override protected void paintComponent(Graphics g) {
initShape();
super.paintComponent(g);
}
@Override protected void paintBorder(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getForeground());
g2.draw(shape);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
@Override public boolean contains(int x, int y) {
//initShape();
return shape.contains(x, y);
}
}
References
this is exactly what i am looking for!!!
ReplyDeletethanks
I'm glad :)
ReplyDelete