0% found this document useful (0 votes)
13 views25 pages

AWT and Swing GUI Programming Examples

The document contains code snippets from 9 Java programs demonstrating the use of various AWT and Swing components. The programs show how to create labels, text fields, checkboxes, radio buttons, menus, scroll panes, combo boxes, trees, tables and progress bars using different layouts like FlowLayout, GridLayout, BorderLayout and CardLayout.

Uploaded by

dshinde02568
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views25 pages

AWT and Swing GUI Programming Examples

The document contains code snippets from 9 Java programs demonstrating the use of various AWT and Swing components. The programs show how to create labels, text fields, checkboxes, radio buttons, menus, scroll panes, combo boxes, trees, tables and progress bars using different layouts like FlowLayout, GridLayout, BorderLayout and CardLayout.

Uploaded by

dshinde02568
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PR1: write a program to demonstrate the use of awt componants like

label,textfild,textarea,button,checkbox,radiobutton
import [Link].*;
import [Link].*;

public class RadioDemo


{
public static void main( String args[] )
{
Frame f = new Frame();
[Link](true);
[Link](400,400);
[Link](new FlowLayout());

Label l1 = new Label("Select Subjects:");

Checkbox cb1 = new Checkbox("English");


Checkbox cb2 = new Checkbox("Sanskrit");
Checkbox cb3 = new Checkbox("Hindi");
Checkbox cb4 = new Checkbox("Marathi");

Label l2 = new Label("Select Gender:");


CheckboxGroup cg = new CheckboxGroup();
Checkbox c1 = new Checkbox("Male",cg,true);
Checkbox c2 = new Checkbox("Female",cg,true);

[Link](l1);
[Link](cb1);
[Link](cb2);
[Link](cb3);
[Link](cb4);
[Link](l2);
[Link](c1);
[Link](c2);
}

Output:
PRACTICAL 2: WRITE A PROGRAM TO DESIGN A FORM
USING THE COMPONENTS LIST AND CHOICE.

import [Link].*;

public class ChoiceDemo


{
public static void main(String args[])
{
Frame f = new Frame();
[Link](400,400);
[Link](true);
[Link](new FlowLayout());

Choice c = new Choice();


[Link]("Maths");
[Link]("Physics");
[Link]("Chemistry");

[Link](c);
}
}
PRACTICAL 3: WRITE A PROGRAM TO DESIGN SIMPLE
CALCULATOR WITH THE USE OF GRIDLAYOUT

import [Link].*;
public class GridDemo
{
public static void main( String args[] )
{
Frame f = new Frame();
[Link](true);
[Link](400,400);
[Link](new GridLayout(2,2));

Font font = new Font("TimesRoman",[Link],25);


[Link](font);

Label l[] = new Label[25];

for(int i = 0 ; i < 25 ; i++)


{
String s = "";
s = [Link](i+1);
Color c = new Color(i,i+10,i+20);
l[i] = new Label();
[Link](c);
l[i].setBackground(c);
l[i].setText(s);
}

for(int i = 0 ; i < 25;i++)


{
[Link](l[i]);
}
}
}
PR4: write a program to create a two level card desk that allows the user to select
componant of panel using cardlayout

import [Link].*;
import [Link].*;
import [Link].*;

public class CardLayoutExample1 extends JFrame implements ActionListener


{

CardLayout crd;

// button variables to hold the references of buttons


JButton btn1, btn2, btn3;
Container cPane;

// constructor of the class


CardLayoutExample1()
{

cPane = getContentPane();

//default constructor used


// therefore, components will
// cover the whole area
crd = new CardLayout();

[Link](crd);

// creating the buttons


btn1 = new JButton("Apple");
btn2 = new JButton("Boy");
btn3 = new JButton("Cat");

// adding listeners to it
[Link](this);
[Link](this);
[Link](this);

[Link]("a", btn1); // first card is the button btn1


[Link]("b", btn2); // first card is the button btn2
[Link]("c", btn3); // first card is the button btn3

}
public void actionPerformed(ActionEvent e)
{
// Upon clicking the button, the next card of the container is shown
// after the last card, again, the first card of the container is shown upon clicking
[Link](cPane);
}

// main method
public static void main(String argvs[])
{
// creating an object of the class CardLayoutExample1
CardLayoutExample1 crdl = new CardLayoutExample1();

// size is 300 * 300


[Link](300, 300);
[Link](true);
[Link](EXIT_ON_CLOSE);
}
}
PRACTICAL 5: WRITE A PROGRAM USING AWT TO CREATE
A MENU BAR WHERE MENUBAR CONTAINS MENU ITEMS
SUCH AS FILE, EDIT, VIEW AND CREATE A SUBMENU UNDER
THE FILE MENU: NEW AND OPEN

import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];

public class MemuDialog extends Frame implements ActionListener ,ItemListener


{
Dialog dialog;
Label l;

MemuDialog()
{
MenuBar mBar = new MenuBar();
setMenuBar(mBar);

Menu file = new Menu("File");


MenuItem new_file = new MenuItem("New");
MenuItem open_file = new MenuItem("Open");
MenuItem save_file = new MenuItem("Save");
new_file.addActionListener(this);
open_file.addActionListener(this);
save_file.addActionListener(this);

[Link](new_file);
[Link](open_file);
[Link](save_file);
[Link](file);

Menu edit = new Menu("Edit");


MenuItem undo_edit = new MenuItem("Undo");
CheckboxMenuItem cut_edit = new CheckboxMenuItem("Cut");
CheckboxMenuItem copy_edit = new CheckboxMenuItem("Copy");
CheckboxMenuItem edit_edit = new CheckboxMenuItem("Paste");
undo_edit.addActionListener(this);
cut_edit.addItemListener(this);
copy_edit.addItemListener(this);
edit_edit.addItemListener(this);

Menu sub = new Menu("Save Type");


MenuItem sub1_sum = new MenuItem("Direct Save");
MenuItem sub2_sum = new MenuItem("Save As");
[Link](sub1_sum);
[Link](sub2_sum);
[Link](sub);
[Link](undo_edit);
[Link](cut_edit);
[Link](copy_edit);
[Link](edit_edit);
[Link](edit);
dialog = new Dialog(this,false);
[Link](200,200);
[Link]("Dialog Box");

Button b = new Button("Close");


[Link](this);

[Link](b);
[Link](new FlowLayout());
l = new Label();
[Link](l);
}

public void actionPerformed(ActionEvent ie)


{
String selected_item = [Link]();

switch(selected_item)
{
case "New": [Link]("New");
break;
case "Open": [Link]("Open");
break;
case "Save": [Link]("Save");
break;
case "Undo": [Link]("Undo");
break;
case "Cut": [Link]("Cut");
break;
case "Copy": [Link]("Copy");
break;
case "Paste": [Link]("Paste");
break;
default: [Link]("Invalid Input");
}
[Link](true);
if(selected_item.equals("Close"))
{
[Link]();
}
}

public void itemStateChanged(ItemEvent ie)


{
[Link]();
}

public static void main(String[] args)


{
MemuDialog md = new MemuDialog();
[Link](true);
[Link](400,400);
}
}
PRACTICAL 6: WRITE A PROGRAM USING SWING TO
DISPLAY A SCROLLPANE AND JCOMBOBOX IN AN JAPPLET
WITH THE ITEMS - ENGLISH, MARATHI, HINDI, SANSKRIT.

import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class JComboBoxDemo extends JApplet implements ItemListener


{
JLabel JLabelObj ;

public void init()


{
setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
JComboBox JComboBoxObj = new JComboBox();

[Link]("Solapur");
[Link]("Pune");
[Link]("Banglore");
[Link]("Mumbai");
[Link](this);

JLabelObj = new JLabel();

add(JComboBoxObj);
add(JLabelObj);
}

public void itemStateChanged(ItemEvent ie)


{
String stateName = (String) [Link]();

[Link]("You are in "+stateName);


}

}
/* <applet code="JComboBoxDemo" height="400" width="400"> </applet> */
PRACTICAL 7: WRITE A PROGRAM TO CREATE A JTREE.

import [Link].*;
import [Link].*;
import [Link].*;

public class JTreeDemo


{
public static void main(String[] args) {

JFrame JFrameMain = new JFrame();


[Link](true);
[Link](400,400);

DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("India");

DefaultMutableTreeNode maharashtraNode = new DefaultMutableTreeNode("Maharashtra");


DefaultMutableTreeNode gujrathNode = new DefaultMutableTreeNode("Gujrath");
[Link](maharashtraNode);
[Link](gujrathNode);

DefaultMutableTreeNode mumbaiSubNode = new DefaultMutableTreeNode("Mumbai");


DefaultMutableTreeNode puneSubNode = new DefaultMutableTreeNode("Pune");
DefaultMutableTreeNode nashikSubNode = new DefaultMutableTreeNode("Nashik");
DefaultMutableTreeNode nagpurSubNode = new DefaultMutableTreeNode("Nagpur");

[Link](mumbaiSubNode);
[Link](puneSubNode);
[Link](nashikSubNode);
[Link](nagpurSubNode);

JTree tree = new JTree(rootNode);

[Link](tree);
}

}
PRACTICAL 8: WRITE A PROGRAM TO CREATE A JTABLE.

import [Link].*;
import [Link].*;
import [Link].*;

public class JTableDemo


{
public static void main(String[] args) {

JFrame JFrameMain = new JFrame();


[Link](true);
[Link](400,400);

String colHeads[] = {"ID","Name","Salary"};

Object data[][] = {
{101,"Amit",670000},
{102,"Jai",780000},
{101,"Sachin",700000}
};
JTable JTableObj = new JTable(data,colHeads);

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(JTableObj,v,h);

[Link](jsp,[Link]);

//[Link](JTableObj);
}
}
PRACTICAL 9: WRITE A PROGRAM TO LAUNCH A
JPROGRESSBAR

import [Link].*;
import [Link].*;

public class JProgresBarDemo


{
JProgressBar JProgressBarObj;
int i=0,num=0;

JProgresBarDemo()
{
JFrame JFrameMain = new JFrame();

[Link](true);
[Link](400,400);
[Link](new FlowLayout());

JProgressBarObj = new JProgressBar(0,2000);


[Link](0);
[Link](true);

[Link](JProgressBarObj);
}

public static void main(String[] args)


{
JProgresBarDemo jpd = new JProgresBarDemo();
[Link]();
}

public void iterate()


{
while(i<=2000){
[Link](i);
i =i+20;
try
{
[Link](150);
}
catch(Exception e)
{

}
}
}

}
Write a Program using JProgressBar to show the progress of Progressbar when user
clicks on JButton.
Ans:

import [Link].*;
import [Link].*;
import [Link];
import [Link];

public class JProgressBarApplet extends JApplet implements ActionListener


{
JProgressBar JProgressBarObj;
JButton JButtonObj;
int i=0;

public void init()


{
setSize(400,400);
setVisible(true);
setLayout(new FlowLayout());

JButtonObj = new JButton("Click Me");


[Link](this);

JProgressBarObj = new JProgressBar();


[Link](true);
[Link](0);

add(JButtonObj);
add(JProgressBarObj);
}

public void actionPerformed(ActionEvent ie)


{
[Link]();
}

public void iterate()


{
while(i<=2000)
{
[Link](i);
i=i+20;
try
{
[Link](150);
}
catch(Exception e)
{}
}
}
}
/* <applet code="JProgressBarApplet" height="400" width="400">
</applet>
*/
PRACTICAL 10: WRITE A PROGRAM TO DEMONSTRATE
STATUS OF KEY ON APPLET WINDOW SUCH AS
KEYPRESSED, KEYRELEASED, KEYUP, KEYDOWN

import [Link].*;

import [Link].*;

import [Link].*;

public class KeyEventDemo extends Applet implements KeyListener

String msg = "";

public void init()

addKeyListener(this);

public void keyReleased(KeyEvent k)

showStatus("Key Released");

repaint();

public void keyTyped(KeyEvent k)

showStatus("Key Typed");

repaint();

public void keyPressed(KeyEvent k)

{
showStatus("Key Pressed");

repaint();

public void paint(Graphics g)

[Link](msg, 10, 10);

/*

<applet code="KeyEventDemo" height="400" width="400">

</applet>

*/
PRACTICAL 11: WRITE A PROGRAM TO DEMONSTRATE
VARIOUS MOUSE EVENTS USING MOUSELISTENER AND
MOUSEMOTIONLISTENER INTERFACE

import [Link].*;
import [Link].*;
import [Link].*;

public class MouseColor extends Applet implements MouseMotionListener


{
public void init()
{
addMouseMotionListener(this);
}

public void mouseDragged(MouseEvent me)


{
setBackground([Link]);
repaint();
}

public void mouseMoved(MouseEvent me)


{
setBackground([Link]);
repaint();
}

}
/*
<applet code="MouseColor" width=300 height=300>
</applet>
*/
PRACTICAL 12: WRITE A PROGRAM TO DEMONSTRATE THE
USE OF JTEXTFIELD AND JPASSWORDFIELD USING
LISTENER INTERFACE

A)
import [Link].*;
import [Link].*;

public class JPasswordChange


{
public static void main(String[] args) {
JFrame f = new JFrame();

[Link](true);
[Link](400,400);
[Link](new FlowLayout());

JPasswordField pf = new JPasswordField(20);

[Link]('#');

[Link](pf);
}

B)
import [Link].*;

import [Link].*;

public class PassDemo extends JPanel

// create an object of the JLabel class

JLabel lblName;

JLabel lblPasswd;

// create an object of the JPassword class

JTextField txtName;

JPasswordField txtPasswd;
public PassDemo()

lblName = new JLabel("Enter the User Name: ");

txtName = new JTextField(10);

lblPasswd = new JLabel("Enter the Password: ");

txtPasswd = new JPasswordField(10);

[Link]('*');

// Add tooltips to the text fields

[Link]("Enter User Name");

[Link]("Enter Password");

//Add labels to the Panel.

add(lblName);

add(txtName);

add(lblPasswd);

add(txtPasswd);

public static void main(String[] args)

// calls the PassDemo constructor.

PassDemo demo = new PassDemo();

// set the text on the frame

JFrame frm = new JFrame("Password Demo");


[Link](demo);

/* setSize() method is used to specify the width and height of the frame */

[Link](275,300);

// To display the Frame

[Link](true);

WindowListener listener = new WindowAdapter()

public void windowClosing(WindowEvent winEvt)

[Link](0);

}; // End of WindowAdaptor() method

// Window listener activates the windowClosing() method

[Link](listener);

} // End of main() method

} // End of class declaration


PRACTICAL 14: WRITE A PROGRAM TO DEMONSTRATE THE
USE OF LNETADDRESS CLASS AND ITS FACTORY METHODS.

import [Link];
import [Link];
import [Link];

public class RetriveIP


{
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter Host Name: ");


String host = [Link]();

try
{
InetAddress ip = [Link](host);

[Link]("IP Adress of Computer is:"+[Link]());


}
catch(UnknownHostException e)
{
[Link](e);
}

}
}
PRACTICAL 15: WRITE A PROGRAM TO DEMONSTRATE THE
USE OF URL AND URLCONNECTION CLASS AND ITS
METHODS

import [Link];

import [Link];

public class URLRetrive

public static void main(String[] args) throws MalformedURLException {

URL url = new URL("[Link]

[Link]("Authority: "+ [Link]());

[Link]("Default Port: "+ [Link]());

[Link]("File: "+ [Link]());

[Link]("Path: "+ [Link]());

[Link]("Protocol: "+ [Link]());

[Link]("Reference: "+ [Link]());

}
PRACTICAL 18: WRITE A PROGRAM TO INSERT AND
RETRIEVE THE DATA FROM DATABASE USING JDBC

Program to insert data:

// Program to Insert Data into Database

import [Link];
import [Link];
import [Link];
import [Link];

public class InsertStaticOracle


{
public static void main(String args[])
{
Statement st = null;
Connection connection = null;
try{
[Link] driverObj = new [Link]();

String url = "jdbc:oracle:thin:@localhost:1521:XE", username = "System" ,password = "pass";

connection =[Link](url,username,password);

if(connection!=null)
[Link]("Connection established successfully");

st = [Link]();

String qry = "Insert into Student values(104 ,'Atharva Agrawal','Dhule')";

int count = [Link](qry);

[Link](count+" Statement Created Successfully ");


}
catch(Exception e)
{
[Link]();
}
finally{
try
{
if(st != null)
[Link]();
if(connection != null)
[Link]();
}
catch(SQLException e){
[Link]();
}
}
}
}
Program to retrieve data:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class SelectOracle


{
public static void main(String args[]) throws SQLException
{
[Link]("Step 1: ");
[Link] obj = new [Link]();
// [Link]([Link]);
[Link]("Driver loaded successfully");

[Link]("Step 2: ");
String url="jdbc:oracle:thin:@localhost:1521:XE",uname="SYSTEM" , password="Atharva007";
Connection connection = [Link](url,uname,password);
if(connection!=null)
[Link]("Connection Established Successfully");
else
[Link]("Connection Not Established Successfully");

[Link]("Step 3: ");
Statement st = [Link]();
[Link]("Statement Referenced ");

[Link]("Step 4: ");
[Link]("Step 5: ");
String qry = "select * from Student";
ResultSet rs = [Link](qry);
[Link]("rs: "+rs);

[Link]("Step 6: ");
[Link]("Id\tName\taddress");
while([Link]())
{
int x = [Link](1);
String y = [Link]("Name");
String s = [Link](3);
[Link](x+"\t"+y+"\t"+s);
}

[Link]("Step 7: ");
[Link]();
[Link]();
[Link]();
}
}
Database:
PRACTICAL 22: WRITE A SERVLET PROGRAM TO SEND
USERNAME AND PASSWORD USING HTML FORMS AND
AUTHENTICATE THE USER

[Link]:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MySrv extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
[Link]("<HTML>");
[Link](" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
[Link](" <BODY>");

//Getting HTML parameters from Servlet

String username=[Link]("uname");
String password=[Link]("pwd");

if(([Link]("atharva")) && ([Link]("agrawal")))


{
[Link](" <h1> Welcome to "+username);
}
else
{
[Link](" <h1> Login fails ");
[Link](" <a href='./[Link]'> Click for Home page </a>");
}
[Link](" </BODY>");
[Link]("</HTML>");
[Link]();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
doPost( request,response);
}

[Link]:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>

<BODY bgcolor='#e600e6'>
<form action='./MySrv' method="post">
<center> <h1> <u> Login Page </u></h1>

<h2> Username : <input type="text" name="uname"/>

Password : <input type="password" name="pwd"/>

<input type="submit" value="click me"/>


</center>
</form>
</body>
</HTML>

[Link]:

<web-app>

<servlet>

<servlet-name>MySrv</servlet-name>

<servlet-class>MySrv</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>MySrv</servlet-name>

<url-pattern>/MySrv</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>[Link]</welcome-file>

</welcome-file-list>

</web-app>

Common questions

Powered by AI

MenuBars and nested MenuItems present a structured and accessible way for users to navigate functionality in GUI applications. In MemuDialog, the MenuBar organizes commands into logical categories ('File', 'Edit', 'View'), each containing relevant MenuItems, such as 'New' or 'Open'. Submenus like 'Save Type' under 'Edit' further compartmentalize actions, aiding user experience by grouping actions logically and reducing overwhelm, making complex applications easier to use .

The init() method in a Java Applet serves as the initialization subroutine, which is called each time an applet is loaded or reloaded. In the JComboBoxDemo program, the init() method sets up the GUI components such as the JComboBox and JLabel, arranging them using a FlowLayout and making the applet visible. This method is crucial in preparing the applet's visual components and configuring their initial properties before interaction begins .

CardLayout allows for stacking multiple panels on top of each other, effectively letting one panel take up the full space at a time, which is ideal for creating wizard-style or step-through screens. This is different from the FlowLayout where components are added sequentially and wrap based on the container's width, and GridLayout which organizes components in a grid format. CardLayout's ability to switch between panels with actions makes it more suitable for dynamic GUI interfaces where panels need to change based on user interaction, such as the CardLayoutExample1 program that observes clicks to switch views .

Using Checkboxes within a CheckboxGroup for a gender selection feature ensures that only one checkbox can be selected at a time, mimicking the behavior of radio buttons. This is beneficial for mutually exclusive options, such as gender, ensuring the user does not accidentally select inconsistent options. In the RadioDemo program, the two gender options ('Male' and 'Female') utilize a CheckboxGroup to allow only one selection, making the user interface more logical and error-resistant .

A JScrollPane with a JTable provides scrolling capabilities, allowing users to view large tables that might not fit within the visible area of a window. This enhances usability by ensuring that data is accessible through scrolling. The JScrollPane dynamically manages the addition of scrollbars as needed, optimizing the interface depending on the size of the JTable. This was demonstrated in the JTableDemo program, where the JTable was wrapped in a JScrollPane to enable vertical and horizontal scrolling when required .

The JTree component is highly effective for representing hierarchical data due to its tree structure, which allows users to expand and collapse sections to view sub-nodes. In the JTreeDemo example, hierarchical geographical data (such as cities in states) is visualized effectively using DefaultMutableTreeNode objects to create parent-child relationships. This approach is beneficial for navigating complex data structures, as it provides a clear, intuitive view for users interacting with nested categories .

A dynamic JComboBox in a JApplet provides users with an interactive dropdown menu that changes based on user selection or other inputs, improving flexibility and efficiency in data selection. In JComboBoxDemo, users can choose from various cities, and the JComboBox dynamically updates a JLabel to reflect the current selection, providing immediate feedback. This interaction is beneficial in scenarios requiring frequent data input changes, as it minimizes user input errors and enhances the application's responsiveness .

The KeyEventDemo program uses event methods to distinguish each key action effectively: 'keyPressed' activates when any key is initially pressed; 'keyReleased' fires when the key is lifted, and 'keyTyped' processes when a character-producing key sequence concludes. The program's use of these listeners allows detecting all phases of key interaction, facilitating comprehensive input handling which is particularly useful in interactive applications requiring detailed user input analysis .

In the JProgressBarApplet example, clicking the JButton triggers an ActionListener that calls the 'iterate()' method. This method uses a loop to incrementally update the JProgressBar's value, simulating progress animation. The 'setValue()' method adjusts the progress bar's current position, and 'setStringPainted(true)' displays the percentage of completion. The loop includes a 'Thread.sleep(150)' call to slow down updates, enhancing the visible transition effect, representing a smooth, gradual progression .

Using plaintext for username and password validation presents significant security risks, including interception and unauthorized access during data transmission. In the MySrv example, the servlet directly compares plaintext credentials from HTTP requests without encryption or hashing, exposing them to potential eavesdropping or MITM (Man-in-the-Middle) attacks. Secure applications should implement HTTPS for encrypted data transfer and store hashes of passwords rather than raw values to mitigate these risks .

You might also like