In this post, we will see Swing in Java with Example | GUI Programming With Swing in Java | Java Swing Tutorial for Beginners
Watch following video:
Watch on YouTube: https://www.youtube.com/watch?v=vn7ySvMb3Ds
What is Swing?
Swing is an API used for creating Graphical User Interface.
How Swing is different from Applet?
Applet doesn't have main method. So it can not be used as an independent application. We have to use Applet alongwith other applications for e.g. webpages. For Applet, we require web browser(e.g. AppletViewer or other browser) to display its result. Pop-ups we see in many websites are the Applets.
While Swing has main method. It can be used as independent application. Swing is mostly used to develop stand-alone application.
How To Create Swing Application?
We have to extend class JFrame into a class where we have to give details of Frame. We find JFrame class in javax.swing package. That's why we need to import javax.swing.*.
We have to call setVisible() method with argument "true" to show frame. We need to call setSize() method with arguments "Horizontal Size" and "Vertical Size".
We can add components Label, TextField, Button by creating their respective objects and passing them to add() method as argument.
In Swing, by default, Layout is CardLayout. In CardLayout, components overlap with each other. Hence, if we want to use multiple components, we have to use other Layouts like FlowLayout, GridLayout etc. To change Layout, we have to use method setLayout() and pass object of particular Layout class as an argument.
When we run Java program, we get a frame. This frame has symbol for close, minimize,maximize. If we click on close symbol, frame will get closed but program which is running will not get closed/stopped. To close this program(process) as soon as we click on close symbol, we need to call setDefaultCloseOperation() method. We have to pass constant to this method which is given by JFrame.EXIT_ON_CLOSE . This constant has value 3.
Go through the following example: Your all concepts related to Swing will get cleared. Output is given at the end of this post.
public class SwingExample
public static void main(String args)
Abc obj=new Abc();
class Abc extends JFrame
JLabel l1=new JLabel("Full Name:");
JTextField t1=new JTextField();
JLabel l2=new JLabel("Class:");
JTextField t2=new JTextField();
JLabel l3=new JLabel("College:");
JTextField t3=new JTextField();
JLabel l4=new JLabel("City");
JTextField t4=new JTextField();
JButton b1=new JButton("Submit");
JButton b2=new JButton("Reset");
How To Run:
parag@parag-Inspiron-N4010:~/Desktop/prog$ javac SwingExample.java
parag@parag-Inspiron-N4010:~/Desktop/prog$ java SwingExample
Check Java Swing program for addition of two numbers in this post http://www.comrevo.com/2017/08/java-swing-program-for-addition-of-two-numbers.html .
Check other posts on Java Programming in this link http://www.comrevo.com/2017/08/java-programming.html
Post a Comment