Add to Google Reader or Homepage

JButton - An Example

Creating a Button in JFrame


Buttons are one of the most commonly used components in any UI based application.In this post we are going to see how to create a button and how to assign a event handler to that button.


Creating a button in java is very simple and it involves four steps,

1.Creating the button

2.adding the button to the container(frame or panel)

3.creating the Listeners for buttons

4.associating those Listeners to the buttons

First Step,creating the button is as easy as follows

Jpanel p=new JPanel();
JButton button=new JButton("NEXT");
p.add(button);

Here you have to note one thing,simply creating a button will not register itself with the Event Listener and its your job to register a button with the Event Handler and to define actions that you desire when you click the button,

I have included a simple program that explains how to create buttons and registering with a Event handler

Program


Flowlayoutmain

import javax.swing.*;
class Flowlayoutmain
{
public static void main(String args[])
{
Flowlayoutdemo f1=new Flowlayoutdemo();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}


Flowlayoutdemo

import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;


class Flowlayoutdemo extends JFrame
{
public Flowlayoutdemo()
{
setTitle("FlowLayoutDemo");
setLocationByPlatform(true);
setSize(400,400);
BorderLayout b=new BorderLayout();
setLayout(b);

JPanel p=new JPanel();
JTextArea ta=new JTextArea(12,35);
p.add(ta);
Border bo=BorderFactory.createEtchedBorder();
p.setBorder(bo);
add(p,BorderLayout.SOUTH);


JPanel jp=new JPanel();

//creating the buttons
JButton button1=new JButton("NEXT");
JButton button2=new JButton("CANCEL");

//adding the buttons to the panel
jp.add(button1);
jp.add(button2);
add(jp,BorderLayout.CENTER);

//creating the Listeners for buttons

BListener b1=new BListener("You have pressed NEXT Button",ta);
BListener b2=new BListener("You have pressed CANCEL Button",ta);

//associating those Listeners to the buttons
button1.addActionListener(b1);
button2.addActionListener(b2);

}
}

class BListener implements ActionListener
{
public BListener(String text,JTextArea a)
{
 txt=text;
 a1=a;
}
public void actionPerformed(ActionEvent e)
{
a1.setText(txt);
}
private String txt;
private JTextArea a1;
}

Output:



The first two steps seems to be very easy and so let's go to the third step

Creating the listeners

 What do you mean by listeners?,In general a listener is someone who listens to you when you do something(speaking,dancing..)

                   In this case,a listener is an object that listens to a button click.

Now,we need to create the Listeners(listener objects) for each buttons along with the actions that you desire.To create a Listener object,the class of the object must implement the ActionListener interface. 

So I have created objects for the class BListener which implements ActionListener interface and specified the actions that I would like to do.


BListener b1=new BListener("You have pressed NEXT Button",ta);
BListener b2=new BListener("You have pressed CANCEL Button",ta);

 Associating the listeners to  the buttons


After creating the listeners you have to associate them with the buttons using the addActionListener() method as follows,

button1.addActionListener(b1);
button2.addActionListener(b2);



ClassNotFoundException thrown when deserializing an object

classNotFoundException thrown because of deserialization

 

I guess you may all know about ClassNotFoundException which is thrown,when the class that we try to load(using forName() and loadClass()) is not available in the classpath. Note that this exception is different from the NoClassDefFounderror which is thrown when the SystemClassLoader  tries to load in the class that is not available. 

In both cases the cases one thing remains same, i.e, the class definition is not available in the classpath.

Here,this ClassNotFoundException is thrown  when deserializing an object. Lets see how?

Have you ever wondered what really happens when we serialize an object?You may have read that the state of the object is stored in the stream.What do they really mean by storing the state of the object?

Actually what happens is the values of non-static  and non-transient fields of the class, corresponding to the object that we serialize is stored in the stream in binary format.

When you try to deserialize an object we are not actually retrieving the objects from the stream.We are constructing a new object with the state information provided in the stream    ( i.e, field values stored in the stream).
  
 "we can  construct an object only if the class is available"

So at the time of deserialization we need the actual class to construct that object. Thus it is obvious that if the class is not available in the classpath then this exception would be thrown.

I have explained this with an example as follows.

Program:


 People


import java.io.*;
import java.util.*;
class People implements Serializable
{
String Name;
}
 

Employee


import java.io.*;
import java.util.*;
class Employee extends People
{
public static void main(String[] args) throws Exception{
People p=new People();
p.Name="ganesh";
ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("out.ser"));
os.writeObject(p);
}
}

 
 These two programs are  used to create an object of people and serialize it into the stream.

The following program tries to deserialize the people object from the stream and see what happens when the people class is not available in the classpath.


PeopleRead


import java.io.*;
import java.util.*;
class PeopleRead
{
public static void main(String args[])throws Exception
{
FileInputStream fis = new FileInputStream("out.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o =ois.readObject();// throws ClassNotFoundException
ois.close();
fis.close();
}
}


Exception thrown:

 

Exception in thread "main" java.lang.ClassNotFoundException: People
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Unknown Source)
        at java.io.ObjectInputStream.resolveClass(Unknown Source)
        at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
        at java.io.ObjectInputStream.readClassDesc(Unknown Source)
        at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
        at java.io.ObjectInputStream.readObject0(Unknown Source)
        at java.io.ObjectInputStream.readObject(Unknown Source)
        at PeopleRead.main(PeopleRead.java:9)
 


Actually i have changed the classpath and compiled & executed it.As you see the line Object o =ois.readObject(); in the above program,it tries to read the state information from the stream and tries to reconstruct the object.Since the class definition is not available i got this exception. You may ask why the hell i am going to change the classpath. 

By the way you are not going to change the classpath, and these kind of exceptions will be thrown when you are dealing with Remote Method Invocation(RMI) where in,the class definition, may reside on the other virtual machine.

Java FlowLayout - An Example

Using FlowLayout in our Application

We all (may be) know that in java,Layout Manager is used to lay the components in the containers like Frame,panel. There are many layout managers available in java among which FlowLayout manager is also the one.

To apply a particular Layout to a container.

  • First we need to create the particular Layout Object which we would like to apply in our application.
  •   Next pass the Layout Object as an argument to the setLayout() method.

We can create the FlowLayout in two ways

1. Using the default FlowLayout constructor like as follows,


Example:


FlowLayout f=new FlowLayout();
setLayout(f);


2.This method involves using the parameterized constructor of the FlowLayout class which provides some flexibility in laying the components in the container.


Example:


FlowLayout f=new FlowLayout(int align);
setLayout(f);


FlowLayout f=new FlowLayout(int align,int hori-dist,int vert-dist);
 setLayout(f);


align-Specifies some of the predefined constants like FlowLayout.CENTER , Flow Layout.LEFT,FlowLayout.RIGHT.

hori-dist- Specifes the horizontal distance between the components as well as between the edges of the container and the components.

Veri-dist- Specifies the vertical distance between the components as well as between the edges of the container and the components.


Program:


FlowLayoutdemo.java

import java.util.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;

class Flowlayoutdemo extends JFrame
{
public Flowlayoutdemo()
{
setTitle("FlowLayoutDemo");
setLocationByPlatform(true);
setSize(400,400);

// creation of base panel
JPanel  jp=new JPanel();//By default JPanel has FlowLayout Manager
jp.setBorder(new LineBorder(Color.RED,10,false));

//creation of the first panel for having components
JPanel jp1=new JPanel();
jp1.setBorder(new LineBorder(Color.ORANGE,10,true));
JButton button1=new JButton("NEXT");

//creatin of the second panel for having components
JPanel jp2=new JPanel();
jp2.setBorder(new LineBorder(Color.GREEN,10,true));
JButton button2=new JButton("BACK");

jp1.add(button1);
jp2.add(button2);


jp.add(jp1);
jp.add(jp2);

add(jp);
}
}

 

Flowlayoutmain.java

import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
class Flowlayoutmain
{
public static void main(String args[])throws IOException
{
Flowlayoutdemo f1=new Flowlayoutdemo();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
 

As you see the first program which i have shown above i haven't used the default constructor for creating flow layout  because JPanel has FlowLayout by default.

If you use the default constructor for creating flowlayout then all the components that you would add will be placed at the top initially at CENTER  until you specify the alignment.

The output of the above program would be as follows.






 If you see the output you can notice that there is no considerable distance between the components and also if you keep on adding components to the container then the components will be positioned in the second row and so on.







If you use the parameterized constructor for creating flowlayout it enables you to position the components at the specified location if the pixel coordinates of the top-left corner of the component is given.

For example, if you set the basepanel( object jp used in the first program) with the following flowlayout configuration,

JPanel  jp=new JPanel(new FlowLayout(FlowLayout.CENTER,20,100));

Here we have used CENTER alignement,hori-dist=20,vert-dist=100.These values would modify the output as follows.




 
Here i would like to highlight you one thing that the "position of the components will not be affected by the alignment you use because they are positioned according to the horizontal distance and vertical distance that you have specified".

 

 

JPanel Border

How to add Borders to JPanel

An user interface design, normally requires us to include many a number of components in the application window(JFrame and JPanel in our case). In which there may be a need to visually separate the components in order to reduce the fuzziness.

Say for an example,If you have ever worked in the MS Word you could have noticed in the print window that the components used to select the page range will be separated from the components used to select the number of copies with the help of borders.

Thus borders helps in  visually grouping the components that are related,thereby making things clear.

In this Post,I will show you how to add borders to a panel and what are the options available to us in enhancing the UI design.

To add borders to our Panel,


 1.First create the object of Border class.

2.By using the static methods of BorderFatory class you can create borders like 

a.Titled Border - use BorderFatory.createTitledBorder()

b.EtchedBorder-use BorderFatory.createEtchedBorder()

c. Empty Border-use BorderFatory.createEmptyBorder()

d.Lowered Bevel Border-use BorderFatory.createLoweredBevelBorder()

e.Raised Bevel Border...-use BorderFatory.createRaisedBevelBorder()

except SoftLevelBorder which is available as separate class.

3. Then assign the resultant object to the Border object  created in the first step.

4. Using the panel's setBorder (Border b) method  we can set the desired border for our panel by passing the Border object as argument.



Example:


Border b= BorderFactory.createTitledBorder("My Border");
panel.setBorder(b);


Check out the API of BorderFactory class to know the signature of various methods which i have mentioned before.


A simple program that explains how to add borders to a panel is shown below.

 

Program


Borderexframe.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.border.*;
class Borderexframe extends JFrame
{
public Borderexframe()
{
setTitle("BorderframeDemo");
setSize(400,400);
setLocationByPlatform(true);
setLayout(new GridLayout(3,1));// create sections for three panels

 

// firstpanel and its components

firstpanel=new JPanel();
JButton b1=new JButton("LineBorder");
JButton b2=new JButton("Etched");
JButton b3=new JButton("TitledBorder");
add(firstpanel);
createBorder(b1,new LineBorder(Color.GREEN,5,true));
createBorder(b2,BorderFactory.createEtchedBorder(EtchedBorder.RAISED,Color.RED,Color.ORANGE));
createBorder(b3,BorderFactory.createTitledBorder(new SoftBevelBorder(EtchedBorder.RAISED),"MY BORDER",TitledBorder.CENTER,TitledBorder.TOP));


//second panel and its components

secondpanel=new JPanel();
JRadioButton yellow=new JRadioButton("Yellow");
JRadioButton blue=new JRadioButton("BLUE");
secondpanel.add(yellow);
secondpanel.add(blue);
createRadioButton(yellow,Color.YELLOW);
createRadioButton(blue,Color.BLUE);
secondpanel.setBorder(BorderFactory.createTitledBorder(new SoftBevelBorder(EtchedBorder.RAISED),"BACKGROUND",TitledBorder.CENTER,TitledBorder.ABOVE_TOP));
add(secondpanel);

// thirdpanel and its components

thirdpanel=new JPanel();
add(thirdpanel);
}

 
public void createBorder(JButton b,final Border bo)
{
firstpanel.add(b);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
thirdpanel.setBorder(bo);
}
});
}

public void createRadioButton(JRadioButton rb,final Color c)
{

secondpanel.add(rb);
rb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
secondpanel.setBackground(c);
}
});

}
private final JPanel firstpanel;
private final JPanel secondpanel;
private final JPanel thirdpanel;
}
 
 

Borderframemain.java

import javax.swing.*;
import java.awt.*;

class Borderframemain
{
public static void main(String args[])throws Exception
{
Borderexframe f1=new Borderexframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}


Output



We can also be able combine one or more borders to produce the combined effect.To do so use the following method.


BorderFactory.CompoundBorder(Border Out-side,Border in-side)


Java BorderLayout - An Example

BorderLayout

 

Border Layout is one of the Layouts available in java to arrange the components in the Containers like JFrame and JPanel. Lets see,how to use the BorderLayout  in this post.

This Layout helps us to position the components in the Container but does not provide much flexibility compared to other Layouts like FlowLayout and GridBagLayout in rendering the Components.

Because flowlayout enables us to specify the exact coordinate Position of the component and GridBagLayout is more flexible but quite complex compared to other layouts.


 This Layout has five Constants like 

BorderLayout.NORTH - To render the components in the Northern (or Top) position of the container.

BorderLayout.SOUTH- To render the elements in the Southern (or bottom) position of the container.

BorderLayout.CENTER- To render the elements in the Center of the Container.

BorderLayout.EAST- To lay the components in the left side of the Container.

BorderLayout.WEST- To lay the elements in the right side of the container


If you do not explicitly mention the position of the components then center position will be chosen.

Look at the following program,

Program:


Borderframe.java

import javax.swing.*;
import java.awt.*;
import java.util.*;
import javax.imageio.*;
import java.io.*;
class Borderframe extends JFrame
{
public Borderframe()
{
setTitle("BorderLayoutDemo");
setSize(200,200);
setLocationByPlatform(true);

JButton b1=new JButton("B1");
JButton b2=new JButton("B2");
JButton b3=new JButton("B3");
JButton b4=new JButton("B4");
JButton b5=new JButton("B5");
add(b1,"Center");
add(b2,"North");
add(b3,"West");
add(b4,"South");
add(b5,"East");
}
}


 
 
Borderframemain.java

import javax.swing.*;
import java.awt.*;

class Borderframemain
{
public static void main(String args[])throws Exception
{
Borderframe f1=new Borderframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}


 
Here i have created five buttons for each of the five positions in the frame and if you compile and execute the program then you will get the output as follows.





If you see the output you can be able to infer one thing that these components(buttons) occupies the entire region of the frame in the given position.For example,Button b2 occupies the entire Northern region resulting in a big button.If the frame size is large then you would get even larger button.

But in a good UI design we would not want Buttons like these. So,in these kind of situations FlowLayout helps us to deal with  this problem. But using FlowLayout needs us to know the exact Coordinates to locate the components.

So we need to combine  these two layouts to produce the desired output.How to combine?

1.First create a panel which has default layoutmanager as FlowLayout and then add the component to the panel.

2.Next add the panel into the JFrame to the desired location.

Though you combine this two layouts you would not get the desired  output because the components at CENTER seems to be slightly closer to the Northern region as follows.





So you have to set the horizontal and vertical distance between the components in order to get the desired result using the BorderLayout(int hori-dist,int vert-dist) constructor.

I have edited the above program to produced the desired output and it as follows,



Borderframe.java

import javax.swing.*;
import java.awt.*;
import java.util.*;
import javax.imageio.*;
import java.io.*;
class Borderframe extends JFrame
{
public Borderframe()
{
setTitle("BorderLayoutDemo");
setSize(200,200);
setLayout(new BorderLayout(0,20));//horiz-dist=0 and vert-dist=20
setLocationByPlatform(true);
 

JPanel p[]=new JPanel[5];
for(int i=0;i<5 br="br" i="i">p[i]=new JPanel();


JButton b[]=new JButton[5];
for(int i=0;i<5 br="br" i="i">b[i]=new JButton("B"+i);


for(int i=0;i<5 br="br" i="i">p[i].add(b[i]);
 

add(p[0],"Center");
add(p[1],"North");
add(p[2],"West");
add(p[3],"South");
add(p[4],"East");

}

}
 



OUTPUT 







  Note:


1. The ContentPane of any JFrame has BorderLayout as the default Layout Manager.

2. The Center Component will not be rendered until all the surrounding components are drawn.


 

JFrame background image

Adding background image to JFrame

 

Adding background image to a JFrame is simple with the availability of ImageIO class.

Two steps are essential in drawing an image to the JFrame.

1.First we need to create an object of Image class that refers to the image,which we would like to draw on our JFrame.

2.Next we need to add the code for drawing the image in the paintComponent()method of the JComponent class,

Since we would like to draw an image,drawImage(Image img,int x,int y, Image Observer  obj) method of the Graphics class would be enough.

img - it represents the Image object which refers to the actual image.

x and y- denotes the distance from the left and top of the JFrame respectively.

obj- It is an object of ImageObserver which is used to keep track of the rendering process and we need not worry about it as we can simply set it to null.

Here i have included a sample program that adds an background image to the frame.

 

Program:


Firstframe.java

import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setTitle("My FirstFrame");
setSize(200,200);
setLocationByPlatform(true);
Addimage im=new Addimage("car1.gif");
add(im);
}
}
 

Myframe.java

import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
 

Addimage.java

import javax.swing.*;
import java.util.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
class Addimage extends JComponent
{
public Addimage(String imgfile)
{
try
{
img=ImageIO.read(new File(imgfile));
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
g.drawImage(img,0,0,null);
}
private Image img=null;
}
 

  Output:

 

 
 

 

Things to be remembered:


If you want to draw any component to a frame then you are supposed to use the paintComponent(Graphics g) method.

You need not invoke this method as it will be automatically invoked when the frame is made visible or resized.

Inside this method you have to add your drawing code.
 

jframe fullscreen

How to set JFrame to fullscreen


To set the size of the frame to full screen, you should have knowledge about the screen size of your laptop,PC. But you cannot ensure that the frame size will cover the entire screen on an other device,since screen size of the devices may vary.

In order to get rid of this problem Abstract Window Toolkit library has been provided.It enables you to calculate the screen size of the current device.

See the following program which will create a frame that covers the full-screen and it will work fine on any PC or laptop.

Program:

 

Myframe.java

import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
 


Firstframe.java

  
import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
Toolkit k=Toolkit.getDefaultToolkit();
Dimension scr=k.getScreenSize();
int swidth=(int)scr.getWidth();
int sheight=(int)scr.getHeight();
setSize(swidth,sheight);
setTitle("My FirstFrame");
}
}



jFrame Size

How to size a frame?


The size of the frame also plays an important role in a good user-interface design.By default the frame that you would create will be of size 0x0 pixels.So you need to set the size of the frame manually.

There are two methods available for this purpose 

 1.setSize(int width,int height)    
 2.setBounds(int x,int y,in width,int height)

If you call the setSize() method with the desired width and height as arguments
then the frame will be generated with the given specifications.

Program:


Myframe.java

import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
 

 Firstframe.java

import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);// frame of width 200 pixels and height 200 pixels
setLocation(50,50);
setTitle("My FirstFrame");
}
}
 

If you execute this program with the java launcher then you would see a frame of 200x200 pixels.

By using the setBounds() method you could be able to define the size of the frame along with its position.So there is no need of a separate setLocation() method to specify the location of the frame.Here i have edited the program shown above as follows.

Program:


Firstframe.java

import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setBounds(50,50,200,200);//Locates the frame at the desired location                                                                               with the given size.
setTitle("My FirstFrame");
}
}
 

JFrame Position

How to position a JFrame


when you create a frame,by default the frame is positioned at the top-left corner of your screen,until you specify the desired location.

To get the attention of the user this default orientation of the frame is not enough.So we need to relocate the frame according to the user needs.There are three methods to relocate a frame.

Method 1:

 

You can use the setLocation(int x,int y) method of the Component class to locate the frame to your desired location.

In this method,first argument specifies the distance from the left side of the screen(pixels) and the second argument specifies distance from the top of the screen(pixels).

Program:

 

Myframe.java

import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}

Firstframe.java

import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);
setLocation(50,50);// Here i have specified the location as (50,50)
setTitle("My FirstFrame");
}
}

 
 Specifying the location of the frame is same as specifying a point in a graph,where in the (x,y) co-ordinates specify the starting point from where the frame should be drawn.

 

Method 2:

 

There is a method(function) named setLocationByPlatform(boolean b) available in the Windows class which decides the suitable location for the frame (randomly)rather than  letting you to  choose the desired location.

If you call this method with a boolean value of true then the platform will pick a suitable location.

In the above program instead of using the setLocation() method use this setLocationByPaltform(true) method.

Method 3:

 

Using the setBounds(int x,int y,int width,int height) you can choose the desired location and the desired size of the frame.

Description:

int x- distance from the left side of the screen
int  y-distance from the top of the screen

int Width - specifies the width of the frame

int Height- specifies the height of the frame.

In the program that i have mentioned before instead of using the setLocation() method use the setBounds() method.

JFrame example

JFrame

 Before explaining how to create a frame first let's have a quick overview of what is meant by a frame?

A frame is a primary window or a top-level window within which you would add your GUI components like  Buttons,Text Fields, images etc.Thus a frame acts as a container for the user interface elements.

To create a frame you need to import the javax.swing library and extend the JFrame class.Have a look at the following program to understand how to create a frame.

Program


Firstframe.java

import javax.swing.*;
import java.util.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);
setTitle("My FirstFrame");
}
}
 

Myframe.java
import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}

The above program shown is an simple example of creating a frame without enclosing any components in it.





If you compile and execute this program then you would see a simple window in the top-left corner of the screen as shown above.

If you want to know how to position a frame? click here.. 

You may also be interested in sizing a frame which is essential for a good user-interface design.
 

An Overview

 
There are certain methods do exist which are essential for creating a frame properly.

As you see,

setTitle(String obj)- used to set the title for the frame,the title should be a string object.

setSize(int width,int height)- It is also obvious that this method is used to set the size of the frame.If you do not specify the size of the frame then a frame of size 0x0 pixels will be generated.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)- This method is used to terminate the program when the user closes the frame.If this method is not used then when the user closes the frame then the window will disappear but the program would not get terminated.

setVisible(true)- This method is used to make the frame visible on the screen.By default  this property of the frame is set to false.So if you do not set this property of a frame to be true manually,your frame will not be visible.


Creating Executable JAR

Executable JAR's


Executable JAR's are Java Archive Files(JAR) that contains an application(along with its resources) which can be executed by using either java program launcher or in case of windows by simply double-clicking the jar file.

One of the main-difference between an ordinary jar file and an executable jar file is that it has an attribute named "Main-Class" associated with it in the manifest file.

The Main-Class attribute is used to specify the entry point in the jar file. 

"The entry point denotes the class that you want to execute when a use double-clicks a jar file or uses java launcher to execute the file".

The entry point must denote the main class i.e, a class that contains public static void main(String args[]). 

There are two possible ways to create an executable JAR.

1.When creating a jar file use the option e to create an entry point in the Manifest.

See the following sample to understand the above method of creating an executable jar file.

 Example:

 

C:\>jar cvfe Add1.jar Add Add.class
added manifest
adding: Add.class(in = 1450) (out= 872)(deflated 39%)

In this example,

Add1.jar-  name of the JAR file.

Add-   it is the entry point in the manifest i.e the class that is to be executed (Main class)

Add.class-The resource file that i have included in the JAR.

If you see the manifest of the generated JAR then you can identify a Main-Class attribute as follows.

Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)
Main-Class: Add

2. The Second method for generating a executable jar would be quite difficult compared to the first method.

Here you have to create your own Manifest file as follows:

2.1.Open the NotePad and type the attributes as i have shown below.

Manifest-Version: 1.0

Main-Class: Add

Note:

 

 There are certain things which i feel quite worth to be mentioned here when creating a manifest file.

1.When writing the attributes ensure that one line space is available between them.Simply press the Enter key double time immediately after writing an attribute.

2.If you do not leave one line space or leave some extra space between the attributes then  the desired manifest file would not be generated.

2.2  After finished writing the attributes save the file with .mf extension.

Now we can create the executable jar file using the following command line.


C:\>jar cvfm Add.jar addmanifest.mf Add.class
added manifest
adding: Add.class(in = 1450) (out= 872)(deflated 39%)

Add.jar- name of the jar file.
addmanifest.mf- manifest file that i have created by using the notepad.
Add.class- resource file that i have added into the jar file.


Remember one thing,in windows executing a jar using a launcher or by double-clicking it will not generate a shell window.



 
java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top