Swing in java tutorial with example - The Idle Coder

Swing in java tutorial with example

Here is tutorial about how to create your first java application by using concept of swing in java. Here we have made simple java swing application.

What is swing in java?

Well, Swing is a GUI widget toolkit for Java. Swing is a set of program components for Java programmers that provide the ability to create graphical user interface ( GUI ) components

First of all you need to Import javax.swing.* library file. As you all know, it contains all components that can be used while making java application using swing. Well, we will use concept of Applet and awt in this program.

Source code is below.

Catch this: How to make your first java application using abstract window toolkit

Catch also: Top free iphone application 

Read also: Top best antivirus for android

Source code for making Simple application (swing in java example)



import javax.swing.*;
public class swing1 extends JApplet
{
public void init(){

JTabbedPane jtb=new JTabbedPane();
jtb.addTab("Cities",new citiesPanel());
jtb.addTab("age",new agePanel());
jtb.addTab("Phone",new phonePanel());

getContentPane().add(jtb);
}
}
class citiesPanel extends JPanel
{
public citiesPanel(){
JButton jb1=new JButton("ahmedabad");
JButton jb2=new JButton("surat");
JButton jb3=new JButton("pune");

add(jb1);
add(jb2);
add(jb3);
}
}
class agePanel extends JPanel{

 public agePanel(){

JCheckBox cb1=new JCheckBox("<18");
JCheckBox cb2=new JCheckBox(">18");
add(cb1);
add(cb2);
}
}

class phonePanel extends JPanel{

public phonePanel(){

JComboBox jcb=new JComboBox();

jcb.addItem("Apple");
jcb.addItem("Samsung");
jcb.addItem("Nokia");
jcb.addItem("Micromax");

add(jcb);
}
}

Also read: Download head first java latest edition


Html file for java swing application


<html>
<head>
<title> Swing applet </title>
</head>
<body>
<applet code="swing1.class" width=100 px height=100 px>
</applet>
</body>
</html>

Output of swing in java application

Swing in java with example



Logic


First of all we have included java swing library file. Then we have created one public class which can easily extend JApplet class so that it can directly use JApplet class's features. As you see in output image, we want to create tab menu. So we have used JTabbedPane for creating tab menu object. Then we have added some inner tab buttons in it. Inside all add Tab functions, we have declared one inner class having particular name. After finishing swing1.java file, we have to make one html file, which clearly include applet code in it. You can see that code in file swing2.html. There is no main class! You can try different components in this java swing application. If you have still any doubts for swing in java, please mention here by comm
Previous
Next Post »