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…. 😉

Useful Ant build tags

Questions:

How to do following tasks in ant file?

  1. Make zip file.
  2. Run command.
  3. Copy files to remote machine.
  4. Run commands on Remote Linux machine.
  5. Open an input box and respond to input value.
  6. Make an ant call.

Answers:

1. Make zip file:

Following is the xml for making zip file in ant:

<zip destfile="${destination.folder}/zipName.zip">
     <fileset dir= "${Source.folder}" />
</zip>

In here “destfile” is the name and location of the created zip file. Inside fileset tag the dir attricute is used to specify source folder form where all files will be zipped.

2. Run commands:

Here I will show you how to start tomcat in ant file to demonstrate how to run commands in ant. Following is the xml for this:

<exec dir="${tomcat.home}/bin" executable="cmd" os="Windows XP">
     <arg line="/c startup.bat"/>
</exec>

Here “${tomcat.home}” is the path of the tomcat folder. The command is given in “<arg>” tag in “line” attribute.

 

Note: To run following commands you will need JSCH jar.

3. Copy files to remote machine:

If remote machine is in your LAN and you can access it directly as \\remote_machine\path then you can use simple copy command as follows:

<copy file="${source.folder.file} " todir="\\remote\path">
</copy>

To copy files on remote machine that supports SCP use following tag:

<scp file="${source.folder.file} " todir="${remote.user}@${remote.host}:${remote.path.where.to.do.copy}"
       password="${remote.password}" trust="true">
</scp>

In above both commands “file” is the source file which you want to copy with its path. And “todir” is the remote machine folder path where you want to copy the file.

 

4. Run commands on remote machine:

You can use following tag to execute commands on remote Linux machine.

<sshexec host="${remote.host}" username="${remote.username}" password="${remote.password}"
     command="${command.to.run}" trust="true" />

For example to start tomcat use following tag:

<sshexec host="${remote.host}" username="${remote.user}" password="${remote.password}"
         command="sh ${tomcat.home}/startup.sh" trust="true" />

5. Open an input box and respond to input value:

To open an input dialog use following tag:

<input message="Enter id: " addproperty="my.id">
</input>

Here “my.id” in “addproperty” is the variable name which holds input value. Now to check if user has denied to enter value in input:

<condition property="do.abort">
     <equals arg1="n" arg2="${my.id}"/>
</condition>
<fail if="do.abort">Build aborted by user.</fail>

And if user enters value and press OK then after you can refer to entered value as “${my.id}”.

6. Make an ant call:

<antcall target="targetName">
</antcall>

Here “target” is the name of the target that will be executed.

Note: In above examples all values starting with “${”and ending with “}’’ are variables and you may have to put appropriate values in them to successfully run them.

Lightbox Jar

LightBox.jar
--- Jar that helps you providing light box like effect in your desktop 
 application built in swing.

 You may have seen light box effects on a website but very rarely have seen light box effect in a desktop application specifically in applications that are built in java swing.  This jar helps you put light box like effect into your swing application. So now you can also give same light box effect as on your website to your desktop application made in swing.

Light box effect

Light box effect

It’s very simple and easy to use this jar. You just have to create a instance of LightBox class and then call createLightBoxEffect() method on it with desired parameters and have a light box effect in your frame with a JPanel as popup.


This jar contains following 4 classes:

LightBox.java

  • Main class that helps in providing light box like effect using JFrame and JPanel.

LightBoxUtil.java

  • Light box utility class that contains utility methods like giving buzz effect to frame, blinking frame on taskbar, making beep sound, etc.

LightBoxMouseListener.java

  • If light box is modal then this listener will be added to light box so that all mouse clicks and other mouse events comes in this class and not get passed to underlying components. This is the simplest way I thought about making light box effect modal.

LightBoxException.java

  • Exception class for Light box effect jar.

Following is the description of constructor and methods of the class used to provide light box effect in this jar:

Constructors:

public LightBox()

Creates new LightBox instance. By default the lightbox effect is modal.


public LightBox(boolean modal)

Create new LightBox instance. If modal then all components under light box effect will be not able to generate any event until light box panel is closed.

Parameters:

          modal – Whether to make light box effect modal or not.


 Methods:

public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel)

To give a light box effect.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY)

To give a light box effect and show pop up panel on specified location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame)

To give a light box effect with blinking of window on task bar, plays a beep sound and gives buzz effect to frame.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          blink – Whether to blink frame on taskbar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame)

To give a light box effect with blinking of window on task bar, plays a beep sound and gives buzz effect to frame. Also shows pop up panel on specified location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 java.awt.Dimension size)
                          throws LightBoxException

To give light box effect with specified size of light box shade panel and pop up panel’s location.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          size – Size of the light box shade panel.

Throws:

           LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 java.awt.Dimension size)
                          throws LightBoxException

To give light box effect with specified size of light box shade panel.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          size – Size of the light box shade panel.

Throws:

           LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 int panelLocX,
                                 int panelLocY,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame,
                                 java.awt.Dimension size)
                          throws LightBoxException

 To give light box effect with specified size of light box shade panel with additional property flags like playing a beep sound, buzz frame, blink frame on taskbar.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          panelLocX – X value of location of panel.

          panelLocY – Y value of location of panel.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.

          size – Size of the light box shade panel.

Throws:

         LightBoxException – If given size of shade panel is not proper then this exception will be raised.


public void createLightBoxEffect(javax.swing.JFrame frame,
                                 javax.swing.JPanel panel,
                                 boolean blink,
                                 boolean makeSound,
                                 boolean buzzFrame,
                                 java.awt.Dimension size)
                          throws LightBoxException

 To give light box effect with specified size of light box shade panel with additional property flags like playing a beep sound, buzz frame, blink frame on taskbar.

Parameters:

          frame – Frame on which light box effect will take place.

          panel – Panel that will be shown as a pop up in light box effect.

          blink – Whether to blink frame on task bar or not.

          makeSound – Whether to make beep sound or not.

          buzzFrame – Whether to give buzz effect to frame or not.

          size – Size of the light box shade panel.

Throws:

        LightBoxException – If given size of shade panel is not proper then this exception will be raised.


 public void closeLightBox( javax.swing.JFrame jFrame,
                                           javax.swing.JPanel jPanel)

Exist light box effect.

Parameters:

          jFrame – Frame on which light box effect has taken place.

          jPanel – Panel that is shown as a pop up in light box effect.


 Links:

  1. Swing light box source code and test class are shared here.

Feel free to comment for any query or information regarding this jar on this site.

Create a scheduler task in 5 simple steps – java

Most people don’t know how to run some specific task at specific time in java. For example send daily email at 11:59 or do a daily wind up job or weakly database clean up job, etc. So here you will find how to schedule task in java in 5 simple steps.

Before starting first you need to download quartz jar. You can download it from here.

Step-1 Make a class that implements Job interface from quartz jar and implement it’s execute method. In this method define your task that will be executed on time interval.

public class ScheduleTaskHelper  implements Job  {
      public void execute(JobExecutionContext arg0) throws JobExecutionException {
           // define your task here.
      }
}

Step-2 Create another class which will create and start scheduler for this task.

public class ScheduleTask{
       public ScheduleTask()throws Exception{
       }
}

Step-3 To start scheduler task we first need to define a SchedulerFactory and a Scheduler. Following code will do that:

SchedulerFactory sf=new StdSchedulerFactory();
Scheduler sched=sf.getScheduler();

Step-4 Start that scheduler which is done by calling start method of Scheduler as follows:

sched.start();

Step-5 Create a Job of our task, a cron trigger to tell on which time interval it will run and schedule that job in the scheduler.

JobDetail jd=new JobDetail("myjob",  Scheduler.DEFAULT_GROUP,ScheduleTaskHelper.class);
CronTrigger tr=new CronTrigger("myCronTrigger", Scheduler.DEFAULT_GROUP,"0 59 23 ? * *");
sched.scheduleJob(jd, tr);

Note: – Here the string “0 59 23 ? * *” is used to define scheduler time that is on which time our scheduled task will run. Here this string will schedule task that will run daily in 11:59 pm. To know how to write appropriate cron trigger string refer to this.

Make JFrame transparent

How to create a slider for JFrame transparency and make JFrame transparent accordingly?

First create a frame that has a slider in it which will be used to set transparency amount.

import javax.swing.JFrame;
import javax.swing.JSlider;

public class TransparentFrame extends JFrame {
     public TransparentFrame() {
         setTitle("Transparent Frame");
         setSize(400,400);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JSlider slider = new JSlider(JSlider.HORIZONTAL);
         add(slider);
         setVisible(true);
     }
     public static void main(String[] args) {
         new TransparentFrame();
     }
}

Output of this will be:

Now add a change listener to slider so we can monitor it.


slider.addChangeListener(new ChangeListener() {
       @Override
       public void stateChanged(ChangeEvent e) {
       }
});

Now we will write our transparency logic in this method but before we do that first let’s see how to make a JFrame transparent.

To make a JFrame transparent java has a built in utility class that is AWTUtilities. By using methods provided in this class we can make our JFrame transparent. Following is the code for that:

       AWTUtilities.setWindowOpacity(window, floatOpacity);

Arguments:

                  Window – Your frame/window object.

                  floatOpactity – between 0 to 1.  1 for no opacity and 0 for fully transparent.

So now we know that we have to add this logic to slider change event and give sliders value as floatOpacity value. So for that change stateChanged() method with following:

@Override
public void stateChanged(ChangeEvent e) {
      JSlider slider = (JSlider) e.getSource();
      if(!slider.getValueIsAdjusting()){
            AWTUtilities.setWindowOpacity(TransparentFrame.this, slider.getValue());
      }
}

Think it’s done. No we still have to make sure that opacity value doesn’t go beyond its limit that is 0.0f to 1.0f. So for that we have to limit our slider to these values. As slider don’t supports point values we will take values in multiple of 10 and then divide them by 100 to get desired value. For this we will change JSlider declaration and stateChanged like follow:


JSlider slider = new JSlider(JSlider.HORIZONTAL, 10, 100, 100);

Change following line in stateChanged method:


AWTUtilities.setWindowOpacity(TransparentFrame.this, slider.getValue()/100f);

So now when we run this program we see a frame with a slider in it which is set to end. And when we change slider the frame accordingly change its transparency.

Output:-

Note:-

To use AWTUtilities class in eclipse you need to change preference setting or you may have error for accessing restricted classes. To change settings do as follows:

  1. Right click on your project. Select properties.
  2. Select Java compiler and expand it.
  3. Select Errors/Warnings.
  4. Enable project specific settings.
  5. In Deprecated and Restricted API you will find Forbidden References (access rules.) Change it to Warning or Ignore.
Reference:

Also take a look take: Transparent JFrame using JNA

%d bloggers like this: