Professional Documents
Culture Documents
GUIin Java
GUIin Java
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.
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.
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.
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) {
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.
while(rs.next()){
data.addElement(row);
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);
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.