Advertisements

Transparent JFrame using JNA

In Make JFrame transparent I had shown a way to making frame’s transparent using AWTUtilities class. But using that class results in access restriction compile time error, resolution in Eclipse is also shown in that post. Now here is the version using java natives. I have used Java Native Access (JNA) library to call native functions to get the things done.

What is Java Native Access (JNA)?

JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required.JNA allows you to call directly into native functions using natural Java method invocation.

The Code

import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.sun.jna.platform.WindowUtils;

public class TransparentFrame extends JFrame {
   public TransparentFrame() {
      setTitle("Transparent Frame");
      setSize(400,400);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JSlider slider = new JSlider(JSlider.HORIZONTAL, 30, 100, 100);

      slider.addChangeListener(new ChangeListener() {
         @Override
         public void stateChanged(ChangeEvent e) {
            JSlider slider = (JSlider) e.getSource();
            if(!slider.getValueIsAdjusting()){
               WindowUtils.setWindowAlpha(TransparentFrame.this, slider.getValue()/100f);
            }
         }
      });
      add(slider);
      setVisible(true);
   }
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
	 @Override
	 public void run() {
	    new TransparentFrame();
	 }
      });
   }
}

Here WindowUtils class is provided in JNA jar (platform.jar). The method setWindowAlpha of WindowUtils class is used to make a window transparent. First argument of this method is your frame/window and second argument is alpha value. This class also has a method called setWindowTransparent, which can also be used to make window transparent .

Dependencies

You will need following 2 jars to run this program: (Both jar files are available to download on GitHub for JNA.)

  • jna.jar
  • platform.jar

To run above code on Windows, you will need to set “sun.java2d.noddraw” system property before calling the WindowUtils function.

System.setProperty("sun.java2d.noddraw", "true");

Output

Additional Notes

I have tested this code on following machines:

  • Windows XP service pack 3 (32 bit)
  • Windows 7 (32 bit)
  • Cent OS 5 (32 bit)

If you test it on other machines or have code for other machines using JNA for the same functionality then feel free to share it as comment to this post.

Advertisements

Chat bubble in java swing

chatBubble

This article will explain you “how to draw chat bubble in  java swing application?” Chat bubble is same as call-out or thought bubble. Today most of the chat application is showing conversion in this format, so this article will help you to do the same in desktop application made in java swing.

Following class is used to draw first chat bubble: (Arrow at the left side of bubble)

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JPanel;
/**
 * @author harsh
 */
public class LeftArrowBubble extends JPanel {
   private static final long serialVersionUID = -5389178141802153305L;
   private int radius = 10;
   private int arrowSize = 12;
   private int strokeThickness = 3;
   private int padding = strokeThickness / 2;
   @Override
   protected void paintComponent(final Graphics g) {
      final Graphics2D g2d = (Graphics2D) g;
      g2d.setColor(new Color(0.5f, 0.8f, 1f));
      int x = padding + strokeThickness + arrowSize;
      int width = getWidth() - arrowSize - (strokeThickness * 2);
      int bottomLineY = getHeight() - strokeThickness;
      g2d.fillRect(x, padding, width, bottomLineY);
      g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,   RenderingHints.VALUE_ANTIALIAS_ON));
      g2d.setStroke(new BasicStroke(strokeThickness));
      RoundRectangle2D.Double rect = new RoundRectangle2D.Double(x, padding, width, bottomLineY, radius, radius);
      Polygon arrow = new Polygon();
      arrow.addPoint(20, 8);
      arrow.addPoint(0, 10);
      arrow.addPoint(20, 12);
      Area area = new Area(rect);
      area.add(new Area(arrow));
      g2d.draw(area);
   }
}

Following code is to draw second chat bubble. (Arrow at the right side of bubble):

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.geom.Area;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JPanel;
/**
 * @author harsh
 */
public class RightArrowBubble extends JPanel {
   private static final long serialVersionUID = -5389178141802153305L;
   private int strokeThickness = 3;
   private int radius = 10;
   private int arrowSize = 12;
   private int padding = strokeThickness / 2;
   @Override
   protected void paintComponent(final Graphics g) {
      final Graphics2D g2d = (Graphics2D) g;
      g2d.setColor(new Color(0.5f, 0.5f, 1f));
      int bottomLineY = getHeight() - strokeThickness;
      int width = getWidth() - arrowSize - (strokeThickness * 2);
      g2d.fillRect(padding, padding, width, bottomLineY);
      RoundRectangle2D.Double rect = new RoundRectangle2D.Double(padding, padding, width, bottomLineY,  radius, radius);
      Polygon arrow = new Polygon();
      arrow.addPoint(width, 8);
      arrow.addPoint(width + arrowSize, 10);
      arrow.addPoint(width, 12);
      Area area = new Area(rect);
      area.add(new Area(arrow));
      g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
      g2d.setStroke(new BasicStroke(strokeThickness));
      g2d.draw(area);
   }
}

And here is the code for using above 2 classes:

import java.awt.HeadlessException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
 * @author harsh
 */
public class TestPanel extends JPanel {
	private static final long serialVersionUID = 9029457020704524363L;
	private JLabel messageLbl1, userImageLbl1, messageLbl, userImageLbl;
    private JPanel msgPanel1, msgPanel;
    String userImageUrl = "http://cdn1.iconfinder.com/data/icons/nuvola2/22x22/apps/personal.png";
    public TestPanel() throws MalformedURLException {
        userImageLbl = new JLabel();
        msgPanel = new LeftArrowBubble();
        messageLbl = new JLabel();
        messageLbl1 = new JLabel();
        msgPanel1 = new RightArrowBubble();
        userImageLbl1 = new JLabel();

        userImageLbl.setIcon(new ImageIcon(new URL(userImageUrl)));
        messageLbl.setText("Hi, How are you?");

        GroupLayout msgPanelLayout = new GroupLayout(msgPanel);
        msgPanel.setLayout(msgPanelLayout);
        msgPanelLayout.setHorizontalGroup(
            msgPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(msgPanelLayout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(messageLbl)
                .addContainerGap(162, Short.MAX_VALUE))
        );
        msgPanelLayout.setVerticalGroup(
            msgPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(msgPanelLayout.createSequentialGroup()
                .addComponent(messageLbl)
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        messageLbl1.setIcon(new ImageIcon(new URL(userImageUrl)));
        userImageLbl1.setText("I'm Good.");

        GroupLayout jPanel1Layout = new GroupLayout(msgPanel1);
        msgPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(171, Short.MAX_VALUE)
                .addComponent(userImageLbl1)
                .addGap(22, 22, 22))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(userImageLbl1)
                .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(userImageLbl)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                    .addComponent(msgPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(msgPanel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addComponent(messageLbl1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(userImageLbl)
                    .addComponent(msgPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(messageLbl1)
                    .addComponent(msgPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                .addContainerGap(22, Short.MAX_VALUE))
        );
    }
    public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				try {
					JOptionPane.showMessageDialog(null, new TestPanel());
				} catch (HeadlessException e) {
					e.printStackTrace();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
		});
	}
}

At least try it once and feel free to comment about it. 🙂

JTextField with image inside it

The final output will look like following:

textBox_with_image

I applied same logic as one will do with css if it was meant for website. Just 2 simple steps:

  1. Draw the image as background in text box.
  2. Set margin of image width for text inside text box.

For the first step one have to override painComponent method of JTextField as follow:

final BufferedImage image = ImageIO.read(Test.class.getClassLoader().getResource("img/user.png"));
JTextField textField = new JTextField() {
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int centerPoint = (getHeight() - image.getHeight())/2;
        g.drawImage(image, 0, centerPoint, this);
    }
};

And for the second step:

textField.setMargin(new Insets(0, image.getWidth(), 0, 0));

That’s it. When you use it you will see a text box with image at it’s left as shown in above image.

If you are using custom border for text field and and if is overlapping the image then don’t panic just shift your image slightly as follows:

Get textField’s border inset from the left:

final int borderInset = border.getBorderInsets(new JTextField()).left; // here border is the object indicating Border of JTextField.

Now add it to ‘x’ point in drawImage and serMargin method:

//inside first step
g.drawImage(image, borderInset, centerPoint, this);

//second step
textField.setMargin(new Insets(0, borderInset + image.getWidth(), 0, 0));

As final point don’t forget to increase text field’s height according to your image. If you don’t want to bother to calculate then following line might be helpful to you:

textField.setPreferredSize(new Dimension(textField.getWidth(), image.getHeight() + 10));

🙂

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. 🙂

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. 😀

%d bloggers like this: