Advertisements

Infinite progress bars in swing

Following are some infinite progress bars built in java swing 2d using JPanel’s paintComponent(Graphics g) method.

Windows XP

I have seen this kind of loading icon while setting up windows XP, you might have also seen it:
xp_loader
So how one can simulate same in swing? Here is the answer:

/**
 * Some custom infinite progress bars in JPanel using Graphics2D object.
 * @author harsh
 */
public class CustomInfiniteProgressBar extends JPanel {
    private static final long serialVersionUID = 223086939802246968L;
    private static final int DELAY = 100;
    private static final int MAX_AMOUNT = 100;
    private static final int SPACE = 30;
    private static final int NUMBER_OF_RECTS = 5;
    private Timer timer;
    private int value = 0, darkRect = 0;

    public CustomInfiniteProgressBar() {
        timer = new Timer(DELAY, new TimerActionListener());
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        // draw rectangular progress
        int paddingToFrameBorders = 10; //dummy values for position
        int smallerSize = 5, largerSize = 10; //dummy values for rectangle size

        int rectX, rectY;
        for (int i = 0; i < NUMBER_OF_RECTS; i++) {
            rectX = paddingToFrameBorders + i * SPACE;
            rectY = paddingToFrameBorders;
            if(darkRect == i) {
                g2d.fillRect(rectX, rectY, largerSize, largerSize);
            } else {
                // to center smaller rectangle respective to larger rectangle.
                rectX += (largerSize - smallerSize) / 2;
                rectY += (largerSize - smallerSize) / 2;

                g2d.drawRect(rectX, rectY, smallerSize, smallerSize);
            }
        }
    }

    /**
    * Action Listener of Timer.
    */
    private class TimerActionListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            value++;
            if(value == MAX_AMOUNT) { // you can have some condition here to stop the timer.
                timer.stop();
            }
            darkRect = (value % NUMBER_OF_RECTS);
            repaint();
        }
    }
}

Circular infinite progress bar

circles_loading

For this you just have to replace rectangle drawing logic to circle drawing logic and its done:

// global constants
private static final int RADIUS = 30;
private static final int NUMBER_OF_CIRCLES = 10;

private int darkCircle = 0;

//inside paintComponent(g) method
int centerX, centerY; centerX = centerY = 75; //dummy values for position
int circularX, circularY;
for (int i = 0; i < NUMBER_OF_CIRCLES; i++) {
    circularX = centerX + (int) (RADIUS * Math.sin((360 / NUMBER_OF_CIRCLES) * i * 3.14 / 180));
    circularY = centerY + (int) (RADIUS * Math.cos((360 / NUMBER_OF_CIRCLES) * i * 3.14 / 180));
    if(darkCircle == i) {
        g2d.fillOval(circularX, circularY, 10, 10);
    } else {
        g2d.drawOval(circularX, circularY, 10, 10);
    }
}

// in timer action class
darkCircle = NUMBER_OF_CIRCLES - 1 - (value % NUMBER_OF_CIRCLES);

Another example of such progress bar:
circular_loaing_2

for this use following code inside paintComponent(g) everything else will same as above:

//inside paintComponent(g) method
BasicStroke drawingStroke = new BasicStroke(3, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[]{9}, 0);
g2d.setStroke(drawingStroke);
for (int i = 0; i < NUMBER_OF_CIRCLES; i++) {
    circularX = centerX + (int) (RADIUS * Math.sin((360 / NUMBER_OF_CIRCLES) * i * 3.14 / 180));
    circularY = centerY + (int) (RADIUS * Math.cos((360 / NUMBER_OF_CIRCLES) * i * 3.14 / 180));
    if(darkCircle == i) {
        g2d.setColor(new Color(100, 200, 150));
        g2d.drawLine(circularX, circularY, circularX + 10, circularY + 10);
    } else {
        g2d.setColor(Color.black);
        g2d.drawLine(circularX, circularY, circularX + 10, circularY + 10);
    }
}

Arrow shape for progress bar

I’m not sure if following can be used as progress bar, but it can be used for highlighting something or some similar kind of task.
arrow loading highlighting
The code for this as follows:

// inside paintComponent(g) method
for (int i = 0; i < NUMBER_OF_RECTS; i++) {
    if(darkRect == i)
        g2d.fill(getArrowShape(i * 10, 50, 150));
    else
        g2d.draw(getArrowShape(i * 10, 50, 150));
}

// the getArrowShape method
/**
 * Returns arrow shape(a triangle).
 * Points are:
 * A (x + i, y)
 * | \
 * |  \
 * |   \
 * |    C ((x + 10) + i, (y + 10))
 * |   /
 * |  /
 * | /
 * B (x + i, (y + 20))
*/
private Shape getArrowShape(int i, int x, int y) {
    final Polygon result = new Polygon();
    result.addPoint(x + i, y); // A
    result.addPoint(x + i, (y + 20)); // B
    result.addPoint((x + 10) + i, (y + 10)); // C
    return result;
}

That’s all for now.
Hope You like it. 🙂

Advertisements

Drawing Android icon in swing

Hi, I tried to make android robot in java swing. I found 2 ways of doing this:

  1. Get android robot image, and show it as background in panel.
  2. Draw whole robot shape in java 2d graphics.

Here I will demonstrate the second way. The final output will be like this:

android_icon_in_java_swing

There are mainly five shapes used in this:

  1. A half circle shape for the head.
  2. Round rectangles for hands and legs.
  3. Big rectangle for the body.
  4. Lines for antennas.
  5. Small white circles for eyes.

So here is how you do it in java swing using Graphics2d object.  The color used is “r=153, g= 204,  b=0”:

g2d.setColor(new Color(153, 204, 0));

1. First for the head, the half circle:

g2d.fillArc(75, 55, 150, 125, 0, 180); // head circle

2. The body, a big rectangle. But as in the icon the bottom of body has round corner so as a hack added a round rectangle just after the body, with slightly overlap for not showing top round corners of second rectangle.

g2d.fillRect(75, 125, 150, 150); // body
g2d.fillRoundRect(75, 260, 150, 20, 20, 20); // cause bottom of body has round corners

3. Now for the had. It is quite easy, just need to draw 2 round rectangles and position them at the right point.

g2d.fillRoundRect(40, 120, 30, 110, 30, 30); // right hand
g2d.fillRoundRect(230, 120, 30, 110, 30, 30); // left hand

4. For the legs, do the same as done for hand, draw 2 round rectangles with smaller height and position changed to bottom of body.

g2d.fillRoundRect(95, 260, 30, 70, 30, 30); // right leg
g2d.fillRoundRect(175, 260, 30, 70, 30, 30); // left leg

5. For the antennas:

g2d.drawLine(125, 65, 100, 40); // right head antenna
g2d.drawLine(175, 65, 200, 40); // left head antenna

6. And finally for the eyes

g2d.setColor(Color.white); // change the color for the eyes
g2d.fillOval(115, 80, 10, 10); // left eye
g2d.fillOval(175, 80, 10, 10); // right eye

The whole code combined will look like this:

@Override
protected void paintComponent(Graphics g1) {
	Graphics2D g2d = (Graphics2D) g1;
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g2d.setColor(new Color(153, 204, 0));
	g2d.fillArc(75, 55, 150, 125, 0, 180); // head circle
	g2d.fillRect(75, 125, 150, 150); // body
	g2d.fillRoundRect(75, 260, 150, 20, 20, 20); // cause bottom of body has round corners
	g2d.fillRoundRect(40, 120, 30, 110, 30, 30); // right hand
	g2d.fillRoundRect(230, 120, 30, 110, 30, 30); // left hand
	g2d.fillRoundRect(95, 260, 30, 70, 30, 30); // right leg
	g2d.fillRoundRect(175, 260, 30, 70, 30, 30); // left leg
	g2d.drawLine(125, 65, 100, 40); // right head antenna 
	g2d.drawLine(175, 65, 200, 40); // left head antenna

	g2d.setColor(Color.white);
	g2d.fillOval(115, 80, 10, 10); // left eye
	g2d.fillOval(175, 80, 10, 10); // right eye
}

Hope you like it. 😀


And for the people who are interested in first way, here is how you do it. The first way is quite easy, you need to use drawImage method of Graphics.

@Override
protected void paintComponent(Graphics g) {
	Graphics2D g2d = (Graphics2D) g;
	BufferedImage img = null;
	try {
		img = ImageIO.read(TestAndroidIcon.class.getClassLoader().getResource("./android.png"));
		int w = img.getWidth(null);
		int h = img.getHeight(null);
		BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
		Graphics g1 = bi.getGraphics();
		g1.drawImage(img, 0, 0, null);
		g2d.drawImage(bi, null, 0, 0);
	} catch (IOException e) {
		e.printStackTrace();
	}
}

🙂

Circular progress bar in Java Swing

Had you ever got thought of creating a circular progress bar in swing? yes, huh. At first it sounds difficult but then when you start building it then you might found that it is very easy if you have already made an clock application. 🙂

Final result would be like this:

circlePB

We will start by creating a circle animation by use of Timer and overriding paintComponent method of a JPanel:

/**
 * Circular progress bar panel.
 * @author harsh
 */
public class CircularProgressBar extends JPanel {
      private final static int MAX_PROGRESS_AMOUNT = 100;
      private static final int DELAY = 50;
      private Timer timer;
      private int prgValue = 0;

      public CircularProgressBar() {
            timer = new Timer(DELAY, new MyChangeListener());
            timer.start();
      }

      @Override
      protected void paintComponent(Graphics g) {
             Graphics2D g2 = (Graphics2D) g;
             g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
             if (prgValue <= MAX_PROGRESS_AMOUNT) {
                   g.setColor(Color.blue);
                   int angle = -(int) (((float) prgValue / MAX_PROGRESS_AMOUNT) * 360);
                   g.fillArc(0, 0, getWidth(), getHeight(), 90, angle);

            }
     }

     class MyChangeListener implements ActionListener {
         @Override
         public void actionPerformed(ActionEvent arg0) {
             prgValue++;
             repaint();
             if (prgValue >= MAX_PROGRESS_AMOUNT)
                  timer.stop();
        }
    }
}

if you run this you will see something like this:

It was easy, huh. Now the challenging part is to remove inner circular part and make it to view like first image. For that I decide to draw another circle with the same color as background. So here it is:


g2.setColor(getBackground());
g.fillArc(getWidth() / FRACTION / 2, getHeight() / FRACTION / 2,
getWidth() * (FRACTION - 1) / FRACTION, getHeight() * (FRACTION - 1) / FRACTION, 92, angle);

Add this code to paintComponent method and once again run the program. Now you will see something like in first picture.  In above code FRACTION is the width you want for your progress bar. Lesser value of fraction, wider the progress bar. One more difference in 2 fillArc method is in the start angle, in first method it is 90 and in second its 92. This difference will be width of the middle hand.

Here is the testing code:

JFrame frame = new JFrame("Circular Progress Bar by Harry Joy");
frame.add(new CircularProgressBar());
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

Hope you like it. 🙂

Fireworks in swing

firework panel

firework panel

Want to show firework in swing panel, here it is a way to show something like above picture in java swing. It is done by extending JPanel class and overriding its paintComponent method.  To know what it exactly looks like, give it a try and run once. Let me know your feedback. 🙂


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;

/**
 * Panel in which you can see fireworks.
 */
public class FireworkPanel extends JPanel {

private static final long serialVersionUID = 5053650234847311814L;
 private Timer timer;
 private static final int DELAY = 10, DIVIDER = 180, MULTIPLY_FACTOR = 36, LINE_LENGTH = 2, FIREWORK_RADIUS = 75;
 private static final int ARRAY_LENGTH = 5;
 private static int X_CENTER[] = new int[ARRAY_LENGTH], Y_CENTER[] = new int[ARRAY_LENGTH];
 private static Color colors[] = new Color[ARRAY_LENGTH];
 private static final double PI = 3.14159;
 int x[] = new int[10],y[] = new int[10];
 private int x1, moveX, index, color_index;
 List<Integer> xx = new ArrayList<Integer>();
 List<Integer> yy = new ArrayList<Integer>();

public FireworkPanel() {
      x1 = index = color_index = 0;
      moveX = 3;
      timer = new Timer(DELAY, new MyChangeListener());
      timer.start();
      X_CENTER[0]=100;
      Y_CENTER[0]=100;

      X_CENTER[1]=200;
      Y_CENTER[1]=200;

      X_CENTER[2]=300;
      Y_CENTER[2]=300;

      X_CENTER[3]=300;
      Y_CENTER[3]=100;

      X_CENTER[4]=100;
      Y_CENTER[4]=300;

      colors[0] = Color.ORANGE;
      colors[1] = Color.BLUE;
      colors[2] = Color.CYAN;
      colors[3] = Color.RED;
      colors[4] = Color.PINK;

      setBackground(Color.black);
 }

@Override
protected void paintComponent(Graphics g) {
     super.paintComponent(g);
     Graphics2D graphics2d = (Graphics2D) g;
     Stroke stroke = new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 5, new float[]{9},  0);
     graphics2d.setStroke(stroke);
     graphics2d.setColor(colors[color_index]);
     for (int i = 0; i < xx.size(); i++) {
          graphics2d.drawLine(xx.get(i),yy.get(i),xx.get(i)+LINE_LENGTH,yy.get(i)+LINE_LENGTH);
     }
}

class MyChangeListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
     x1 += moveX;
     if (x1 == 0 || x1 >= FIREWORK_RADIUS) {
          x1=0;
          Random random = new Random();
          index = random.nextInt(ARRAY_LENGTH);
          color_index = random.nextInt(ARRAY_LENGTH);
     }
     xx.clear();
     yy.clear();
     for (int i = 0; i < 10; i++) {
         xx.add((int) (X_CENTER[index] + x1 * Math.cos((MULTIPLY_FACTOR * i * PI) / DIVIDER)));
         yy.add((int) (Y_CENTER[index] + x1 * Math.sin((MULTIPLY_FACTOR * i * PI) / DIVIDER)));
     }
     repaint();
   }
}
}

And here is how to test it:

 JFrame frame = new JFrame("Fireworks");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(400, 425);
 frame.setResizable(false);
 frame.setUndecorated(true);
 frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
 frame.setLayout(new BorderLayout());
 JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
 JLabel jLabel = new JLabel("Fireworks By Harry Joy");
 jLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
 panel.add(jLabel);
 frame.getContentPane().add(panel, BorderLayout.NORTH);
 frame.getContentPane().add(new FireworkPanel(), BorderLayout.CENTER);
 frame.setVisible(true);

Hope you like it. 😀

SOAP Client in java

If you are looking for java client for RESTful web service then you should visit this article:

Simple REST client in java

This article will teach you how to create a SOAP client in java. That is creating a client in java which requests soap server (no need to be in java) and get response from it. First create request message as follows:

SOAPMessage message = MessageFactory.newInstance().createMessage();
SOAPHeader header = message.getSOAPHeader();
header.detachNode();

If you have namespace required in SOAP request then add those namespaces to envelope element as follows:

SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
envelope.setAttribute("namspace","namespaceUrl");

You can add as many attribute as you want. Now time to create request message body.
Following body is made assuming that SOAP server where this client will connect will have a public service method called getResponse(name) available.

SOAPBody body = message.getSOAPBody();
QName bodyName = new QName("getResponse");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
SOAPElement symbol = bodyElement.addChildElement("name");
symbol.addTextNode(“Harry joy”);

Now that request message is ready it’s time to connect to soap server and send request. Following code will do this:

SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
SOAPMessage response = connection.call(message, endpoint);
connection.close();

In above code endpoint is the SOAP server URL without “?wsdl”. To parse response you can do as follows:

SOAPBody responseBody = response.getSOAPBody();
SOAPBodyElement responseElement = (SOAPBodyElement)responseBody.getChildElements().next();
SOAPElement returnElement = (SOAPElement)responseElement.getChildElements().next();
if(responseBody.getFault() != null) { //-- If response has any fault.
 	System.out.println(returnElement.getValue()+" "+responseBody.getFault().getFaultString());
}  else  {
   	System.out.println(returnElement.getValue());
}

Here request/response messages are totally dependent on SOAP server, how you have configured it.


Bonus: How to print request/response xml?

String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
	ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
	msg.writeTo(byteArrayOS);
	return new String(byteArrayOS.toByteArray());
}

Use:

System.out.println(getXmlFromSOAPMessage(message));
System.out.println(getXmlFromSOAPMessage(response));

Full source code:

public class SOAPClient {

	private static final String endpoint = "http://localhost/SOAPService/MySoapService";

	public static void main(String[] args) throws SOAPException {
		SOAPMessage message = MessageFactory.newInstance().createMessage();
		SOAPHeader header = message.getSOAPHeader();
		header.detachNode();

		SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
		envelope.setAttribute("namespace","namespaceUrl");

		SOAPBody body = message.getSOAPBody();
		QName bodyName = new QName("getResponse");
		SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
		SOAPElement symbol = bodyElement.addChildElement("name");
		symbol.addTextNode("Harry Joy");

		SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
		SOAPMessage response = connection.call(message, endpoint);
		connection.close();

		SOAPBody responseBody = response.getSOAPBody();
		SOAPBodyElement responseElement = (SOAPBodyElement)responseBody.getChildElements().next();
		SOAPElement returnElement = (SOAPElement)responseElement.getChildElements().next();
		if(responseBody.getFault()!=null){
			System.out.println(returnElement.getValue()+" "+responseBody.getFault().getFaultString());
		} else {
			System.out.println(returnElement.getValue());
		}

		try {
			System.out.println(getXmlFromSOAPMessage(message));
			System.out.println(getXmlFromSOAPMessage(response));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
		ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
		msg.writeTo(byteArrayOS);
		return new String(byteArrayOS.toByteArray());
	}

}

Different button shapes in swing

Make a class that extends JButton and in its constructor write following [Following code is common for all shapes]:

super(label);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);
setContentAreaFilled(false);
  • Round [Circular] buttons:

Circular Button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
           g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillOval(0, 0, getSize().width-1, getSize().height-1);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
     }
     return shape.contains(x, y);
}
  • Triangle buttons:

Triangle button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     int xPoints[] = {getSize().width/2, 0, getSize().width};
     int yPoints[] = {0, getSize().height, getSize().height};
     g.fillPolygon(x3Points, y3Points, xPoints.length);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     int xPoints[] = {getSize().width/2, 0, getSize().width};
     int yPoints[] = {0, getSize().height, getSize().height};
     g.drawPolygon(xPoints, yPoints, xPoints.length);
}
Polygon polygon;
public boolean contains(int x, int y) {
     if (polygon == null || !polygon.getBounds().equals(getBounds())) {
          int xPoints[] = {getSize().width/2, 0, getSize().width};
          int yPoints[] = {0, getSize().height, getSize().height};
          polygon = new Polygon(xPoints,yPoints, xPoints.length);
     }
     return polygon.contains(x, y);
}
  • Oval buttons:

Oval button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillOval(0, getHeight()/8, getWidth(), getHeight()-(getHeight()/4));
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawOval(0, getHeight()/8, getWidth(), getHeight()-(getHeight()/4));
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0, getHeight()/8, getWidth(), getHeight()-getHeight()/4));
     }
     return shape.contains(x, y);
}
  • RoundRect buttons

RoundRect Button

protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
     }
     return shape.contains(x, y);
}
  • Star buttons:

Star button

public static Shape makeStarDesign(int arms, Point center, double r_out, double r_in) {
     double angle = Math.PI / arms;
     GeneralPath path = new GeneralPath();
     for (int i = 0; i < 2 * arms; i++) {
          double r = (i & 1) == 0 ? r_out : r_in;
          Point2D.Double p = new Point2D.Double(center.x + Math.cos(i * angle) * r, center.y + Math.sin(i * angle) * r);
          if (i == 0) path.moveTo(p.getX(), p.getY());
          else path.lineTo(p.getX(), p.getY());
     }
     path.closePath();
     return path;
}
protected void paintComponent(Graphics g) {
     if (getModel().isArmed()) {
          g.setColor(Color.lightGray);
     } else {
          g.setColor(getBackground());
     }
     Graphics2D graphics2d = (Graphics2D) g;
     graphics2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
     graphics2d.fill(makeStarDesign(5, new Point(50,50), 50, 30));
     super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
     g.setColor(getForeground());
     Graphics2D graphics2d = (Graphics2D) g;
     graphics2d.draw(makeStarDesign(5, new Point(50,50), 50, 30));
}
Shape shape;
public boolean contains(int x, int y) {
     if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Area(makeStarDesign(5, new Point(50,50), 50, 30));
     }
     return shape.contains(x, y);
}

More star buttons

Just change the first argument of makeStarDesign to number of arrows you want in star and it will try to draw it for you. 🙂

  • Play buttons:

Play button

      protected void paintComponent(Graphics g) {
		if (getModel().isArmed()) {
			g.setColor(Color.lightGray);
		} else {
			g.setColor(getBackground());
		}
		int xPoints[] = {0, 0, getWidth()};
		int yPoints[] = {0, getHeight(), getHeight()/2};
		g.fillPolygon(xPoints, yPoints, xPoints.length);
		super.paintComponent(g);
	}

	protected void paintBorder(Graphics g) {
		g.setColor(getForeground());
		int xPoints[] = {0, 0, getWidth()};
		int yPoints[] = {0, getHeight(), getHeight()/2};
		g.drawPolygon(xPoints, yPoints, xPoints.length);
	}

	Polygon polygon;
	public boolean contains(int x, int y) {
		if (polygon == null ||
				!polygon.getBounds().equals(getBounds())) {
			int xPoints[] = {0, 0, getWidth()};
			int yPoints[] = {0, getHeight(), getHeight()/2};
			polygon = new Polygon(xPoints,yPoints,xPoints.length);
		}
		return polygon.contains(x, y);
	}
  • Pentagon buttons:

Pentagon button

	int n=5;
	int x[]= new int[n];
	int y[]= new int[n];
	double angle = 2*Math.PI/n;
	protected void paintComponent(Graphics g) {
		if (getModel().isArmed()) {
			g.setColor(Color.lightGray);
		} else {
			g.setColor(getBackground());
		}
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		for(int i=0; i<n; i++) {
			double v = i*angle;
			x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
			y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
		}
		g.fillPolygon(x, y, n);
		super.paintComponent(g);
	}

	protected void paintBorder(Graphics g) {
		g.setColor(getForeground());
		int x0 = getSize().width/2;
		int y0 = getSize().height/2;
		for(int i=0; i<n; i++) {
			double v = i*angle;
			x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
			y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
		}
		g.drawPolygon(x, y, n);
	}

	Polygon polygon;
	public boolean contains(int x1, int y1) {
		if (polygon == null ||
				!polygon.getBounds().equals(getBounds())) {
			int x0 = getSize().width/2;
			int y0 = getSize().height/2;
			for(int i=0; i<n; i++) {
				double v = i*angle;
				x[i] = x0 + (int)Math.round((getWidth()/2)*Math.cos(v));
				y[i] = y0 + (int)Math.round((getHeight()/2)*Math.sin(v));
			}
			polygon = new Polygon(x,y,n);
		}
		return polygon.contains(x1, y1);
	}
  • Diamond button:

Diamond button

Just change value of n in above code to 4.
  • Hexagon button:

Just change value of n in above code to 6.
By changing value of n you will get different shapes like follow:
Different pentagon shapes
  • More buttons:

You just have to change the code for shape everything else is same. So try it yourself…. 😉
%d bloggers like this: