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();
}
}

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment