You are on page 1of 8

Practical in Java: SWING Package & Its Application

import javax.swing.*;
class ourframe extends JFrame{
public ourframe(){
setTitle("Library System"); setSize(300,200); setResizable(false);
}}
class software{
public static void main(String[] args) {
JFrame frame=new ourframe(); //ourframe is a child class of JFrame..!
frame.setVisible(true);
}}
Now, modify the code as given below.
1. Type the code import java.awt.*;
2. Add the following method inside the JFrame class.
private void centerWindow(Window w){
Toolkit tk=Toolkit.getDefaultToolkit(); Dimension d=tk.getScreenSize();
setLocation((d.width-w.getWidth())/2,(d.height-w.getHeight())/2); }

3. Inside the ourframe() constructer, after the code setResizable(false); add the following code.
centerWindow(this); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(); JLabel mylbl=new JLabel("Name");
JTextField nmtf = new JTextField(10); JButton mybtn=new JButton("OK");
panel.add(mylbl); panel.add(nmtf); panel.add(mybtn); this.add(panel);
Compile the code & view the output.
Grid Layout
Adding controls in to a panel is often needs Layouts. There are several layouts in SWING package. Mostly used layout
is Grid Layout, which can be specified with How many columns & how many rows it might have. We can add the layout
in to a panel then we can add the controls in to the panel.

GridLayout mylayout = new GridLayout(4,2); //GridLayout(int rows, int cols)

panel.setLayout(mylayout); //then continue the adding of controls in to the panel

Radio Button: JRadioButton male = new JRadioButton("Male",false); // add female too..!


Then add them in to a buttongroup (Otherwise its a logical error) ButtonGroup g = new ButtonGroup();
g.add(male); g.add(female);

Combobox: JComboBox religion = new JComboBox();


religion.setEditable(false); religion.addItem("Christianity");
religion.addItem("Hinduism"); religion.addItem("Islam");
The above combobox will have three options (as religions) and those options are not editable by users.
Try to get output as following (using Grid Layout & Newly learned controls)
You can add separate panel for each data set (Name Label & TextField together, then, Gender
Label & Radio buttons are together. etc). Those panels also have to be specified with which layout
they have. Finally those panels should be added in to the core-panel. Consider the sample code.
JPanel core_panel = new JPanel(); JPanel usernamePanel = new JPanel();
JPanel passwordPanel = new JPanel(); JPanel buttonPanel = new JPanel();
JLabel uname=new JLabel("username"); JLabel pwd=new JLabel("password");
JTextField un = new JTextField(10); JTextField pw = new JTextField(10);
JButton mybtn=new JButton("OK"); GridLayout sublayout1 = new GridLayout(1,1);
GridLayout sublayout2 = new GridLayout(1,2); GridLayout corelayout = new GridLayout(3,2);
usernamePanel.setLayout(sublayout2); passwordPanel.setLayout(sublayout2);
buttonPanel.setLayout(sublayout1); core_panel.setLayout(corelayout); usernamePanel.add(uname);
usernamePanel.add(un); passwordPanel.add(pwd); passwordPanel.add(pw);
buttonPanel.add(mybtn); usernamePanel.add(pwd);
Events are actions can be done by user (ex: clicking, typing, scrolling, selecting, mouse moving etc.) or happened inside the
system (ex: Interrupts). Often we can see the following events in SWING applications.
1. Click on Button / Image / Panel 2. Select on Combobox / Checkbox / Radio Button 3. Scrolling

To handle these events, hereafter, we have to implement the interface ActionListener by our frame. Then
class ourframe extends JFrame implements ActionListener{}

Also its better to import the awt package with its sub package event as import java.awt.event.*;

Its better to declare the controls (those are having events) as protected and outside the constructer of Frame Class.
Lets do an example for event handling for a Button Click: Below example gives a message-box when the button is clicked.

class ourframe extends JFrame implements ActionListener{


protected JButton mybtn;
public ourframe(){ setSize(300,200); setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel();
mybtn=new JButton("OK"); mybtn.addActionListener(this);
// Once we made an object for JButton, we have to use its addActionListener method by specifying this keyword.
panel.add(mybtn); this.add(panel);}

public void actionPerformed(ActionEvent e){ //an abstract method. Only its body can be defined
if(mybtn==e.getSource()){ //e is an object, & its method is getSource( )
JOptionPane.showMessageDialog(null,"Welcome User"); //An option Pane
}}}
// Then the main-class can be defined

This method actionPerformed(ActionEvent e) can be used to handle ALL EVENTS applied in the frame-class.
Getting Data from User Interface
We can get the data entered in the user interface when the button is clicked. Include the following under the event function.
String name=nmtf.getText(); // nmtf is the textfield object
String gen=""; if(male.isSelected()){gen="Male";} if(female.isSelected()){gen="Female";}
String myreligion=religion.getSelectedItem().toString();
Then we can store these values in to a database..!
However, before that we will look up how we can renew the frame once after the button is clicked. To do that, we better
1. Define a protected void method which includes all of the Panels & Controls inside the frame-class.
a. At its start, we would type as getContentPane().removeAll();
b. At its end, we would type as validate(); setVisible(true);
2. Inside of the constructer of frame-class, we can just call the above method.
3. Once we clicked the button (once the all data went to database), we will call the above method to renew the frame.
Below example has a Label, a TextField, & a Button. Type something in TextField & Click the button. Then observe it
class ourframe extends JFrame implements ActionListener{
protected JButton mybtn; protected JTextField nmtf;
protected void home(){
getContentPane().removeAll(); /*include the setTitle, setSize, setResizable methods here*/
JPanel panel = new JPanel(); JLabel mylbl1=new JLabel("Name");
nmtf = new JTextField(10); mybtn=new JButton("OK"); mybtn.addActionListener(this);
panel.add(mylbl1); panel.add(nmtf); panel.add(mybtn); add(panel); validate();
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(mybtn==e.getSource()){ String name=nmtf.getText();
JOptionPane.showMessageDialog(null,"Welcome "+name+""); home(); }}
public ourframe(){ home(); }
}
class second{
public static void main(String[] args) {JFrame frame=new ourframe();frame.setVisible(true);
}}
Feed Data in to Database
Here the database is taken as MySQL. It will have a Username, Password and a URL(where the database is located).
In Java, in order to do any operation with database, a sql driver class (as it makes the connection), and the sql package
(as it contains the necessary classes for database operations) are needed. Below procedure shows how a Java front end is
used to insert the data in to a MySQL (database) table.

1. A front-end will have two labels, two text-fields as email & password and a Sign Up button.
2. Once we clicked the button, the username & password are going to be fed in to a MySQL database-table.
3. The database-name is mydb and table-name is members.

Its better to design a database before develop the front-end, as given below.
1. Install the MySQL Database either alone or as a component of XAMPP. In default, the username will be root and
the password will be empty ().
2. Create database & table (with the names given above) via the MySQL code given (as the primary key is email).
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE `members` (`email` varchar(255) NOT NULL PRIMARY KEY,
`pword` varchar(255) NOT NULL DEFAULT '');

Now its time to develop the front end. We can easily modify the earlier one as adding the password field as given below.

JLabel pwdlbl=new JLabel("Password"); pwdtxt=new JPasswordField(10);

Add them appropriately inside the panel. Add the following in the method actionPerformed(ActionEvent e){ }...
if(mybtn==e.getSource()){ /*mybtn is the object-name of Sign Up button*/Class driver_class=null;

try{driver_class=Class.forName("com.mysql.jdbc.Driver"); }

catch(ClassNotFoundException f) {

JOptionPane.showMessageDialog(null,"Error in MySQL Driver!");}

try{ String url = "jdbc:mysql://localhost:3306/mydb";

String login = "root"; String password = "";

Connection con = DriverManager.getConnection(url, login, password);

Statement stmt=null; stmt = con.createStatement(); String query=;

query="insert into members(email,pword)values('"+nametxt.getText()+"','"+pwdtxt.getText()+"')";

stmt.executeUpdate(query);

JOptionPane.showMessageDialog(null,"Inserted Successfully..!"); }

catch(SQLException g) { g.printStackTrace();

JOptionPane.showMessageDialog(null,"Connection Error!");
}}

Update Data in a Database via Java Front-end (Ex: Update the password for a given email)
The updating is differed from inserting only when its SQL query is changed as given below. Modify the code as...
query=" update members set pword='"+pwdtxt.getText()+"' where email='"+nametxt.getText()+"'";
Showing MySQL Table in JPanel
Now, lets try to display a MySQL table in to a SWING Panel (thereby JFrame). A typical Search & Display results would
be an example for this task. This example shows to search the all records of a user in a MySQL table, based on his/her email
address. Following steps illustrate the procedure.

1. Connect the Database & Execute the query as SELECT * FROM tablename WHERE email= user@gmail.com
2. Then the query gives a Row-Data (in that table) which is going to assign a certain object called ResultSet.
3. Count the No. of columns of Row-Data (as meta-data) by using another type of object ResultSetMetaData.
4. Using a for loop based on the column-count, display the columns of table.
5. Using next()method in a while loop of the object of ResultSet, its individual data can be displayed.
6. To add each column and each data of ResultSet in JTable, a certain object called Vector would be used.

Below code explains the above procedure. Assume the statement stmt has already been configured with connection.

String query="select * from members where email='"+t.getText()+"'"; // t.getText() carries the search-key.

ResultSet rs = stmt.executeQuery(query); ResultSetMetaData md = rs.getMetaData();

int columnCount = md.getColumnCount(); Vector columns = new Vector(columnCount);

Vector data = new Vector(); for(int i=1; i<=columnCount;i++){columns.add(md.getColumnName(i));}

while(rs.next()){

Vector row = new Vector(columnCount);

for(int j=1; j<=columnCount; j++){ row.add(rs.getString(j));}

data.addElement(row);

JTable showtable = new JTable(data, columns);

showtable.setPreferredScrollableViewportSize(new Dimension(500, 300));

showtable.validate();
The table is preferred to be inside of Scrolling Pane because the object ResultSet may carry more than one row. Then...
JPanel p2=new JPanel(); GridLayout n1=new GridLayout(1,1); p2.setLayout(n1);

JTable table = new JTable(data, columns);

table.setPreferredScrollableViewportSize(new Dimension(500, 300)); table.validate();

ScrollPane scrollPane = new JScrollPane(table); p2.add(scrollPane); add(p2); validate();

setVisible(true);

Once the search button gets clicked, Textfield contains the email address of a user, passes it to the ActionEvent method.
The method removes all of previous panel(p1) and show a new panel (p2) which contains the table with data of ResultSet.
Therefore its obvious to include the getContentPane().removeAll(); method once the button is clicked.

Hence, if the search doesnt give any table rows, the above code can be modified as adding the
if(rs.getRow()==0)as it gives a JOptionPane.showMessageDialog with No entries found etc.

* * * * * * * * * * * * * * * * * * * * *
If the keyword is Primary Key, then the resulted data can be easily displayed similar with the data-entry panel was. Try
the idea given below, to develop a Simple Data Entry & View tool.
1. MySQL table contains 5 columns: Name, gender, date of birth, email and password. The primary key is email.
2. Prepare a Data Entry Tool to enter the data of several users given above, and feed the data of few users.
3. Prepare a Search & Display Tool to search view the entire data of a user, by entering his/her email address.
4. Once the data is viewed, there would be a Button to bring back the search panel, as it gets clicked.
5. At last, merge the above Tools (Data Entry & Search & Display) in to one program.
Then, there would be three panels as...
o First Select the option whether the user is going to enter new data or search a data
o Second Data Entry Panel or Data Search Panel
o Third Results viewing Panel once after the data has been found in the table.

You might also like