Java introduced swing concept to give a response to deficiency present in java awt. The AWT defines the basic set of controls, windows, and dialog boxes that support usable, but limited graphical interface.
As AWT uses native resources they are called as heavy weight components, and swing are light weight components. Presently most of programmers prefer swing to awt.
This doesn`t mean that AWT are replaced by swing.To become a swing programmer you have to learn AWT has many of awt components are used in swings.
In this tutorial you will learn both awt and swing simultaneously.
Now, lets start with basic one. How to write a swing?
Fallow these steps:
1.First create a frame, using
JFrame jfrm=new JFrame("Frame name here");
2.Set the initial size for the frame, using object created for JFrame
jfrm.setSize(210,600);
3.Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If you don`t write this code, when swing window is closed the application will not close.IF you write this application will be closed when window is closed.
4.Create a text-based label on frame
JLabel jlab=new JLabel("Any message you want to write on frame");
5.Now add label to content pane.
jfrm.add(jlab);
If you don`t write this code label will not be displayed on frame.
6.To display the frame.
jfrm.setVisible(true);
7. Set the layout
jfrm.setLayout(new FlowLayout());
You are done, create a thread in main.
See the example here to display a simple message.
import java.awt.*; import javax.swing.*; class JavaSwing1{ public void display(){ //create frame JFrame jfrm=new JFrame("Swing Application"); //set size jfrm.setSize(200,200); //wen closed? jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //set the layout jfrm.setLayout(new FlowLayout()); //set visible jfrm.setVisible(true); JLabel jlab=new JLabel("A simple swing in java blog for beginners"); //add to frame`spane jfrm.add(jlab); } public static void main(String j[]){ //creating thread SwingUtilities.invokeLater(new Runnable(){ public void run(){ JavaSwing1 obj=new JavaSwing1(); obj.display(); } }); } }
See how to compile swing in Eclipse.
Explanation:
The code in main method causes the JavaSwing1 object to create on the event dispatching thread
rather than on main thread.
Generally swing programs are event driven.For that we us thread, even if you don`t use thread and directly you can call the method in main.
output screen is here
See swing applet program here
This program get an easy idea about swing. Thank you very much.
ReplyDeleteThanks.. It gave a basic idea :)
ReplyDelete