Tuesday, September 3, 2013


Toolkit is a class in awt package. It is useful when you wan to read image file to display in a component, get screen dimension, get screen resolution, or get data that is stored in a clipboard object.

Reading image file
To get an image in your local disk to display on a component, you can use the getImage(String path) method of the Toolkit class. The code fragment reads the image file called image02.png in drive D and displays it in the JLabel object.

Image img=Toolkit.getDefaultToolkit().getImage("d:/image02.png");
JLabel lbl=new JLabel();
lbl.setIcon(new ImageIcon(img));

Getting the screen dimension
Sometimes, you might want to know the width and the height of the screen so that you can find the center point of the screen to place text, a component, or image. The code fragment below displays a JFrame window at the center of the screen.

class Show extends JFrame{
Show(String title){
Dimension ds=Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)ds.getWidth()/2-this.getWidth()/2;
int y=(int)ds.getHeight()/2-this.getHeight()/2;

Getting the screen resolution
To get the screen resolution in dots-per-inch, you need to use the getScreenSolution method of the Toolkit class. The code fragment below read the screen resolution in dots-per-inch.

int resolution=Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println("Screen resolution:"+resolution);

Getting data stored in a clipboard object
When text, image, or even a list of files are copied outside  of your Java applications, those data are stored in a system clipboard object and can be read in to your Java applications. The below code fragment gets the data stored in the system clipboard object and output them to the console window.

class JLabelShow extends JFrame{
JLabelShow(String title){
Container contpane=getContentPane();
contpane.add(new JLabel("Copy something and click the mouse


addMouseListener(new MouseList());


class MouseList extends MouseAdapter{
public void mousePressed(MouseEvent e){
Clipboard cb=Toolkit.getDefaultToolkit().getSystemClipboard();
DataFlavor[] df=cb.getAvailableDataFlavors();

for(int i=0;i<df.length;i++){
Object x=cb.getData(df[i]);
if(x instanceof String) //text data

else if(x instanceof List){
List lst=(List)x;
int size=lst.size();
for(int count=0;count<size;count++){ //list of files
File f=(File)lst.get(count);

else if(x instanceof Image){ //image data
//do something with the image data
}catch(Exception ep){ep.printStackTrace();}


No comments:

Post a Comment