There are two approaches to create a frame:
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.
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 } }
Let's see a swing example by implementing second approach:
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(); } }
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