September 28, 2008

Published September 28, 2008 by

Fullscreen Frame in Java

We may have several frames or windows of various sizes in our Java programs. Sometimes we need fullscreen frame or window. Sometimes we do it by setting the width and height of the frame as same as the screen i.e., monitor like 800 x 640 or 1024 x 768 etc. But what will happen if the monitor is changed or the resolution of the monitor is changed or the program is run on different PCs with different monitor settings?

The solution is to set the frame’s width and height of the screen of the monitor dynamically according to the monitor settings. We can do this simply by writing the following code.

Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
setSize(dimension);


A complete code is given below to make a full screen frame.

import javax.swing.JFrame;
import java.awt.Toolkit;
import java.awt.Dimension;

public class FullscreenFrame extends JFrame {
    public FullscreenFrame() {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(dimension);
        setTitle("A Fullscreen Frame");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String args[]) {
        FullscreenFrame fullscreenFrame = new FullscreenFrame();
        fullscreenFrame.setVisible(true);
    }
}
Read More
Published September 28, 2008 by

Resize and Show Image in Java

Sometimes we need to show images in our Java program and sometimes the images need to be re-sized or scaled; the image may be stored in a file in the storage. Here we will discuss how we can show an image on a label (javax.swing.JLabel) from an image file. We will also discuss how we can scale or resize the image before showing on the label.

Firstly, we have to create an Image object which refers the image file (ImageToBeResized.jpg, in this example). As Image is an interface we cannot instantiate it directly, however getImage(…) method of Toolkit class can help us here to create a reference of java.awt.Image. Static method getDefaultToolkit of Toolkit class can be used to create a reference of Toolkit.

See the following code:

Image image = Toolkit.getDefaultToolkit().getImage("ImageToBeResized.jpg.jpg");


Here it is assumed that the image file and the Java program are in same directory. If the image is in different directory, the full location should be stated in the parameter of getIamge(…) method.

Now, if we need image scaling we may use getScaledInstance(…) of Image. Three arguments need to be passed to the method. First two are new width and height of the image and the last one is the resizing option (any of Image.SCALE_SMOOTH, Image.SCALE_FAST or Image.SCALE_DEFAULT).

See the code below:

Image scaledImage = image.getScaledInstance(200,300,Image.SCALE_DEFAULT);


Here we will get an object of 200 x 300 sized image.

A complete code is given here to demonstrate how we can show image on a label(javax.swing.JLabel) with and without scaling.

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.Container;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class ImageResize {
    JFrame frame = new JFrame();

    JTextField txtFilePath = new JTextField();
    JButton btnBrowse = new JButton("Browse");

    JLabel lblOriginalImage = new JLabel();// original image without scaling will be shown
    JLabel lblResizedImage1 = new JLabel();// scaled image will be shown
    JLabel lblResizedImage2 = new JLabel();

    public ImageResize() {
        Container c = frame.getContentPane();
        c.setLayout(null);

        //set up components size and location
        txtFilePath.setBounds(10, 10, 280, 30);
        btnBrowse.setBounds(300, 10, 80, 30);
        lblOriginalImage.setBounds(10, 60, 280, 250);
        lblResizedImage1.setBounds(300, 110, 200, 200);
        lblResizedImage2.setBounds(510, 160, 150, 150);

        //add the components on the container
        c.add(txtFilePath);
        c.add(btnBrowse);
        c.add(lblOriginalImage);
        c.add(lblResizedImage1);
        c.add(lblResizedImage2);

        txtFilePath.setEditable(false); // the field will not be editable

        //set border for the labels
        lblOriginalImage.setBorder(BorderFactory.createEtchedBorder());
        lblResizedImage1.setBorder(BorderFactory.createEtchedBorder());
        lblResizedImage2.setBorder(BorderFactory.createEtchedBorder());

        btnBrowse.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JFileChooser fileChooser = new JFileChooser(".");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Images", "jpg", "gif", "png");
                fileChooser.addChoosableFileFilter(filter);

                int choice = fileChooser.showOpenDialog(null);

                if (choice == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    txtFilePath.setText(file.getPath());

                    //create Image object from an image file
                    Image originalImage = Toolkit.getDefaultToolkit().getImage(file.getPath());

                    //resize the image according to the label size
                    Image resizedImage1 = originalImage.getScaledInstance(lblResizedImage1.getWidth(),
                            lblResizedImage1.getHeight(), Image.SCALE_DEFAULT);
                    Image resizedImage2 = originalImage.getScaledInstance(lblResizedImage2.getWidth(),
                            lblResizedImage2.getHeight(), Image.SCALE_DEFAULT);

                    //show images on the labels
                    lblOriginalImage.setIcon(new ImageIcon(originalImage));
                    lblResizedImage1.setIcon(new ImageIcon(resizedImage1));
                    lblResizedImage2.setIcon(new ImageIcon(resizedImage2));

                }
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(80, 100, 680, 360);
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        ImageResize ir = new ImageResize();
    }
}
Read More

November 27, 2007

Published November 27, 2007 by

Differences Between Java Terms


Abstract Class
Concrete Class
1. An abstract class cannot be used to instantiate objects.
1. Concrete class can be used to instantiate objects.
2. An abstract class may have one or more subclasses but never an instance
2. Concrete class may have subclasses and instances.
3. Typically an abstract class has one ore more abstract methods.
3. A concrete class doesn’t have any abstract method.
Applets
Servlets
1. Applets are Java programs that can be embedded in HTML documents.
1. Servlets are Java programs that generate content for web pages.
2. Applets run on Java enabled web browsers.
2. Servlets run on Java enabled web servers.
3. Java applets tend to be small programs and are often used to add visual or multimedia effects to web pages.
3. Servlets generate HTML documents that are sent to the client browsers for display. For example, servlets can be used to process an HTML form submitted by a web client and to generate a response page.
Array
Vector
1. An array can contain only one type of data.
1. A Vector can contain references of any type of objects.
2. An array has a fixed size.
2. Size of the Vector can change as needed.
Class Variable (static variable)
Instance Variable (non-static variable)
1. Only one copy of a class variable is shared by all objects of a class
1. Every object has its own copy of all the instance variable of the class
2. A class variable represents class wide information (same to all objects).
2. An instance variable represents information of only one object.
3. A class variable can be accessed through a reference to any object of the class or by qualifying the variable name with the class name and a dot (.).
3. An instance variable can only be accessed through a reference to any object of the class
4. A class variable exists even when no object of the class exists- it is available as soon as the class is loaded into memory at execution time.
4. An instance variable exists only when an object of the class exists.
5. A class variable can be accessed from both the static and non-static context.
5. An instance variable can only be accessed from the non-static context.
Reference: H.M. Deitel and P.J. Deitel (2005) Java How to Program
Primitive Types
Reference Types
1. Primitive types are the fundamental, built in (as keyword) types
1. Reference types are constructed from primitive types either through class definition, interface definition or the use of arrays.
2. A variable of any primitive type contains a single value of the appropriate size and format.
2. A variable of a reference type holds a null reference or a reference to an instance of a class
3. Values of these types cannot be decomposed
3. A reference type can be decomposed into several values.
Read More