Friday, March 20, 2009

Use tray Icon in java



import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;

public class TrayIconDemo {
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//adding TrayIcon.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI() {
//Check the SystemTray support
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon =
new TrayIcon(createImage("images/bulb.gif", "tray icon"));
final SystemTray tray = SystemTray.getSystemTray();

// Create a popup menu components
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");

//Add components to popup menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);

trayIcon.setPopupMenu(popup);

try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}

trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from System Tray");
}
});

aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from the About menu item");
}
});

cb1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb1Id = e.getStateChange();
if (cb1Id == ItemEvent.SELECTED){
trayIcon.setImageAutoSize(true);
} else {
trayIcon.setImageAutoSize(false);
}
}
});

cb2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb2Id = e.getStateChange();
if (cb2Id == ItemEvent.SELECTED){
trayIcon.setToolTip("Ali TrayIcon");
} else {
trayIcon.setToolTip(null);
}
}
});

ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuItem item = (MenuItem)e.getSource();
//TrayIcon.MessageType type = null;
System.out.println(item.getLabel());
if ("Error".equals(item.getLabel())) {
//type = TrayIcon.MessageType.ERROR;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is an error message", TrayIcon.MessageType.ERROR);

} else if ("Warning".equals(item.getLabel())) {
//type = TrayIcon.MessageType.WARNING;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is a warning message", TrayIcon.MessageType.WARNING);

} else if ("Info".equals(item.getLabel())) {
//type = TrayIcon.MessageType.INFO;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is an info message", TrayIcon.MessageType.INFO);

} else if ("None".equals(item.getLabel())) {
//type = TrayIcon.MessageType.NONE;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is an ordinary message", TrayIcon.MessageType.NONE);
}
}
};

errorItem.addActionListener(listener);
warningItem.addActionListener(listener);
infoItem.addActionListener(listener);
noneItem.addActionListener(listener);

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
});
}

//Obtain the image URL
protected static Image createImage(String path, String description) {
URL imageURL = TrayIconDemo.class.getResource(path);

if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
}



Image to be display

Tuesday, March 17, 2009

File Download in java


import java.io.*;
import java.net.*;

/*
* Command line program to download data from URLs and save
* it to local files. Run like this:
* java FileDownload http://schmidt.devlib.org/java/file-download.html
* @author Marco Schmidt
*/
public class FileDownload {
public static void download(String address, String localFileName) {
OutputStream out = null;
URLConnection conn = null;
InputStream in = null;
try {
URL url = new URL(address);
out = new BufferedOutputStream(
new FileOutputStream(localFileName));
conn = url.openConnection();
in = conn.getInputStream();
byte[] buffer = new byte[1024];
int numRead;
long numWritten = 0;
while ((numRead = in.read(buffer)) != -1) {
out.write(buffer, 0, numRead);
numWritten += numRead;
}
System.out.println(localFileName + "\t" + numWritten);
} catch (Exception exception) {
exception.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException ioe) {
}
}
}

public static void download(String address) {
int lastSlashIndex = address.lastIndexOf('/');
if (lastSlashIndex >= 0 &&
lastSlashIndex < address.length() - 1) {
download(address, address.substring(lastSlashIndex + 1));
} else {
System.err.println("Could not figure out local file name for " +
address);
}
}

public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
download(args[i]);
}
}
}

Monday, March 16, 2009

cofee cup in JavaFX

In netbaeans create project for javafx and paste this code:




import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.paint.Color;
import javafx.scene.Group;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.scene.paint.Stop;
import javafx.scene.paint.RadialGradient;

def BGCOLOR = Color.BLACK;

def plateGroup = Group {

translateX: 250
translateY: 300

content: [

// The gray ellipse under the plate
Ellipse{centerX:0 centerY:10 radiusX:160 radiusY:50 fill:Color.DIMGRAY},

// The thin "lip" of the plate (provides a sense of 3D)
Ellipse{centerX:0 centerY:3 radiusX:170 radiusY:50 fill:Color.LAVENDER},

// The large plate ellipse
Ellipse{centerX:0 centerY:0 radiusX:170 radiusY:50
fill:RadialGradient{
centerX:0.5 centerY:0.75
stops:[Stop {offset: 0.0 color: Color.WHITESMOKE},
Stop {offset: 0.5 color: Color.LIGHTGRAY},
Stop {offset: 1.0 color: Color.DARKGRAY}]
}
},

// Recessed plate center
Ellipse{
centerX:0 centerY:5 radiusX:90 radiusY:22
fill:RadialGradient{
centerX:0.5 centerY:0.75
stops:[Stop {offset: 0.0 color: Color.BLACK},
Stop {offset: 0.4 color: Color.LIGHTGRAY},
Stop {offset: 1.0 color: Color.GHOSTWHITE}]
}
}
]
}

def cupGroup = Group {

translateX: 152
translateY: 20
scaleX: 3.0
scaleY: 4.0

content: [
// Cup body
Circle {centerX: 100 centerY: 100 radius: 50
fill: RadialGradient {
centerX: 0.4 centerY: 0.0 focusX: 0.5 focusY:.65, proportional:true
stops: [Stop {offset: 0.0 color: Color.GHOSTWHITE},
Stop {offset: 1.0 color: Color.SILVER}]
}
},

// Cut top of cup
Rectangle{stroke: BGCOLOR fill: BGCOLOR
x:25 y:50 width:150 height:50},

// Outer rim
Ellipse{fill: Color.WHITE centerX:100 centerY:100 radiusX:50 radiusY:8},

// Inner rim
Ellipse{centerX:100 centerY:100 radiusX:48 radiusY:7 //inner rim
fill: RadialGradient {
centerX: 0.4 centerY: 0.0 focusX: 0.5 focusY:.4, proportional:true
stops: [Stop {offset: 0.0 color: Color.GHOSTWHITE},
Stop {offset: 1.0 color: Color.SILVER}]
}
},

// Create "coffee in cup" by intersecting coffee ellipse with inner rim ellipse
ShapeIntersect {

fill:Color.SADDLEBROWN

//Inner Rim
a: Ellipse{centerX:100 centerY:100 radiusX:48 radiusY:7} // inner rim dimensions

//Coffee
b: Ellipse{centerX:100 centerY:102 radiusX:46 radiusY:6} // coffee dimensions
}
]
}

Stage {
title: "Coffee Cup"
width: 500
height: 500
visible: true
scene: Scene {
fill: BGCOLOR
content: [plateGroup,cupGroup]
}
}

Thumbnail Creator



import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ThumbNail2 {


public void createThumbnail(String imgFilePath, String thumbPath,
int thumbWidth, int thumbHeight) throws Exception {

Image image = Toolkit.getDefaultToolkit().getImage(imgFilePath);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
double thumbRatio = (double) thumbWidth / (double) thumbHeight;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = (double) imageWidth / (double) imageHeight;
if (thumbRatio < imageRatio) {
thumbHeight = (int) (thumbWidth / imageRatio);
} else {
thumbWidth = (int) (thumbHeight * imageRatio);
}
BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(thumbPath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
int quality = 100;
param.setQuality((float) quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
out.close();
}

public static void main(String[] args) throws Exception {
new ThumbNail2().createThumbnail("1.jpg",
"thumb1.jpg", 50, 30);
System.out.println("Thumbnail Created Successfully");
}
}

How to use tryIcon in java



package trayicondemo;

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;

public class TrayIconDemo {
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event-dispatching thread:
//adding TrayIcon.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI() {
//Check the SystemTray support
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
final PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon =
new TrayIcon(createImage("images/bulb.gif", "tray icon"));
final SystemTray tray = SystemTray.getSystemTray();

// Create a popup menu components
MenuItem aboutItem = new MenuItem("About");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
Menu displayMenu = new Menu("Display");
MenuItem errorItem = new MenuItem("Error");
MenuItem warningItem = new MenuItem("Warning");
MenuItem infoItem = new MenuItem("Info");
MenuItem noneItem = new MenuItem("None");
MenuItem exitItem = new MenuItem("Exit");

//Add components to popup menu
popup.add(aboutItem);
popup.addSeparator();
popup.add(cb1);
popup.add(cb2);
popup.addSeparator();
popup.add(displayMenu);
displayMenu.add(errorItem);
displayMenu.add(warningItem);
displayMenu.add(infoItem);
displayMenu.add(noneItem);
popup.add(exitItem);

trayIcon.setPopupMenu(popup);

try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}

trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from System Tray");
}
});

aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from the About menu item");
}
});

cb1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb1Id = e.getStateChange();
if (cb1Id == ItemEvent.SELECTED){
trayIcon.setImageAutoSize(true);
} else {
trayIcon.setImageAutoSize(false);
}
}
});

cb2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
int cb2Id = e.getStateChange();
if (cb2Id == ItemEvent.SELECTED){
trayIcon.setToolTip("Ali TrayIcon");
} else {
trayIcon.setToolTip(null);
}
}
});

ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
MenuItem item = (MenuItem)e.getSource();
//TrayIcon.MessageType type = null;
System.out.println(item.getLabel());
if ("Error".equals(item.getLabel())) {
//type = TrayIcon.MessageType.ERROR;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is an error message", TrayIcon.MessageType.ERROR);

} else if ("Warning".equals(item.getLabel())) {
//type = TrayIcon.MessageType.WARNING;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is a warning message", TrayIcon.MessageType.WARNING);

} else if ("Info".equals(item.getLabel())) {
//type = TrayIcon.MessageType.INFO;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is an info message", TrayIcon.MessageType.INFO);

} else if ("None".equals(item.getLabel())) {
//type = TrayIcon.MessageType.NONE;
trayIcon.displayMessage("Ali TrayIcon Demo",
"This is an ordinary message", TrayIcon.MessageType.NONE);
}
}
};

errorItem.addActionListener(listener);
warningItem.addActionListener(listener);
infoItem.addActionListener(listener);
noneItem.addActionListener(listener);

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
});
}

//Obtain the image URL
protected static Image createImage(String path, String description) {
URL imageURL = TrayIconDemo.class.getResource(path);

if (imageURL == null) {
System.err.println("Resource not found: " + path);
return null;
} else {
return (new ImageIcon(imageURL, description)).getImage();
}
}
}