Java Design Pattern
Introduction to Java 10
Introduction to Java 11
Introduction to Java 12

Java Swing Examples

There are two approaches to create a frame:

  1. By creating the Frame class object(association)
  2. By creating a class which extends Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Let's see a swing example by implementing first approach where we are creating one button and adding it on the JFrame object inside the main() method.


SwingDemo.java
import javax.swing.*;  
public class SwingDemo
{ 
	public static void main(String[] args)
	{ 
		JFrame f=new JFrame();  //creating instance of JFrame
												  
		JButton b=new JButton("ok");  //creating instance of JButton 
		b.setBounds(130,100,100, 50);   //x axis, y axis, width, height  
												  
		f.add(b);    //adding button in JFrame 
												  
		f.setSize(350,350);   //400 width and 500 height 
		f.setLayout(null);     //using no layout managers  
		f.setVisible(true);    //making the frame visible
	} 
}
Output:
swing

Let's see a swing example by implementing second approach:

SwingDemo1.java
import javax.swing.*;
public class SwingDemo1 extends JFrame
{    
	JFrame f;
	SwingDemo1()
	{
		JButton b=new JButton("OK");             
		b.setBounds(130,100,100, 50);
												  
		add(b);             
		setSize(350, 350); 
		setLayout(null);
		setVisible(true);  
	} 
	public static void main(String[] args)
	{
		new SwingDemo1(); 
	}
}

About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.


We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc






 PreviousNext