Example of Code in Swing

by | Dec 18, 2020 | Java

Home » Java » Example of Code in Swing

In this article we will discuss Example of Code in Swing in detail using two examples i.e. “Adding buttons to an Application” and “Adding Labels to your Application”.

Adding Buttons to an Application

The following is a simple code of that of a GUI application that will just have a button in the centre titled ‘click’. The button will be given an arbitrary size that can be changed as the program progresses.

import javax.swing.*;

public class DemoSwingExample
{
public static void main (String args [] )
{
//Creating a new frame such that components can be attached later on
JFrame f = new JFrame();

//We will create a new button and title it “click”
JButton b = new JButton ( “click” );
//Setting the width, height, x and y axes of the button
b.setBounds ( 130, 100, 100, 40);

//Adding the button to the main JFrame
f.add(b);

//setting the dimensions of the frame size
f.setSize ( 400, 500);
//using no layout managers
f.setLayout(null);
//making the frame visible
f.setVisible ( true );
}
}

 

Adding Labels to your Application

The following example will show how you can add text labels to the JFrame. If you are familiar with CSS, you can style the text, change fonts, and even add colours and layering to make it look like WordArt.

import javax.swing.*;

public class DemoSwingExample2
{
public static void main (String args [] )
{
//Creating a new frame such that components can be attached later on
JFrame f = new JFrame( “Label Maker” );

//Initializing two labels l1 and l2
JLabel l1, l2;

//Setting the contents of the label
l1 = new JLabel ( “First Label” );
//Setting the dimensions of the label
l1.setBounds (50, 50, 100, 30);
//Setting the contents of the label
l2 = new JLabel ( “Second Label” );
//Setting the dimensions of the label
l2.setBounds (50, 50, 100, 30);

//Now we have to add the two labels to the JFrame
f.add(l1);
f.add(l2);
//setting the dimensions of the frame size
f.setSize ( 400, 500);
//using no layout managers
f.setLayout(null);
//making the frame visible
f.setVisible ( true );
}
}

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author