Sie sind auf Seite 1von 10

Introduction to AWT

The Abstract Windowing Kit

Features implemented by the AWT

• Graphics; define colors, fonts, images, etc.


• Components; GUI components like buttons, windows, menus, etc
• Layout Managers; control the layout of Components in their Containers
• Printing
• Popup menus
• Menu Shortcuts
• Cut and paste

AWT stands for Abstract Windowing Toolkit. It contains all classes to write the program that interface
between the user and different windowing toolkits. You can use the AWT package to develop user
interface objects like buttons, checkboxes, radio buttons and menus etc.
We can use the AWT package to develop user interface objects like buttons, checkboxes, radio buttons
and menus etc.

1. AWT Components
The class component is extended by all the AWT components. More of the codes can be put
to this class to design lot of AWT components. Following are the AWT components:
i. Canvas
ii. Checkbox
iii. Label
iv. Scrollbar
v. TextField

Different types of event in Java AWT


There are many types of events that are generated by your AWT Application. These events are used to
make the application more effective and efficient. Generally, there are twelve types of event are used
in Java AWT. These are as follows :

1. ActionEvent
2. AdjustmentEvent
3. ComponentEvent
4. ContainerEvent
5. FocusEvent
6. InputEvent
7. ItemEvent
8. KeyEvent
9. MouseEvent
10. PaintEvent
11. TextEvent
12. WindowEvent

These are twelve mentioned events are explained as follows :

1. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. It indicates the
component-defined events occurred i.e. the event generated by the component like Button,
Checkboxes etc. The generated event is passed to every EventListener objects that receives such
types of events using the addActionListener() method of the object.

2. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class.
When the Adjustable Value is changed then the event is generated.

3. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. This class
creates the low-level event which indicates if the object moved, changed and it's states (visibility
of the object). This class only performs the notification about the state of the object. The
ComponentEvent class performs like root class for other component-level events.

4. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class. This is
a low-level event which is generated when container's contents changes because of addition or
removal of a components.

5. FocusEvent: The FocusEvent class also extends from the ComponentEvent class. This class
indicates about the focus where the focus has gained or lost by the object. The generated event is
passed to every objects that is registered to receive such type of events using the
addFocusListener() method of the object.

6. InputEvent: The InputEvent class also extends from the ComponentEvent class. This event
class handles all the component-level input events. This class acts as a root class for all
component-level input events.

7. ItemEvent: The ItemEvent class extends from the AWTEvent class. The ItemEvent class
handles all the indication about the selection of the object i.e. whether selected or not. The
generated event is passed to every ItemListener objects that is registered to receive such types of
event using the addItemListener() method of the object.

8. KeyEvent: KeyEvent class extends from the InputEvent class. The KeyEvent class handles all
the indication related to the key operation in the application if you press any key for any
purposes of the object then the generated event gives the information about the pressed key. This
type of events check whether the pressed key left key or right key, 'A' or 'a' etc.

9. MouseEvent: MouseEvent class also extends from the InputEvent class. The MouseEvent
class handle all events generated during the mouse operation for the object. That contains the
information whether mouse is clicked or not if clicked then checks the pressed key is left or
right.

10. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The PaintEvent
class only ensures that the paint() or update() are serialized along with the other events delivered
from the event queue.

11. TextEvent: TextEvent class extends from the AWTEvent class. TextEvent is generated when
the text of the object is changed. The generated events are passed to every TextListener object
which is registered to receive such type of events using the addTextListener() method of the
object.

12. WindowEvent : WindowEvent class extends from the ComponentEvent class. If the window or
the frame of your application is changed (Opened, closed, activated, deactivated or any other
events are generated), WindowEvent is generated.

Introduction to the Swing Set

• Swing is a subset of the Java Foundation Classes (JFC)


• The name "Swing" is not an acronym
• An effort to incorporate many of the features in Netscape's IFC as well as some aspects of IBM
stuff
• First released in March of 1998 with nearly 250 classes and 80 interfaces
• Swing is not a replacement for the AWT.
- Needed to support truly architecture independant interfaces
- Contains more powerful components
• Why bother?
- Increased acceptance (many more supported architectures)
- AWT based on architecture-specific widgits.

Swing Features

• Pluggable Look and Feel


o LnFs are increasingly important
o Similar look of underlying environment
o LnFs for UNIX, Windows, Apple. (Default is called Metal)
o LnFs can be changed at run-time
• Lightweight Components
o Lightweight - components which are not dependant on native source to render
o Heavyweights are unweildy because:
- Equivalent components may act differently on different platforms
- LnF is tied to the host environment
• Many new Components
o Tables
o Trees
o Sliders
o Progress Bars
o Internal Frames
o Text Components (Very nice)
• Tool tips
• Support for undo/redo
• Support for Multiple Document Interfaces (MDI) with InternalFrames

Connecting to a MySQL Database in Java


import java.sql.*;

public class MysqlConnect{


public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Creating a Database Table

import java.sql.*;

public class CreateTable{


public static void main(String[] args) {
System.out.println("Table Creation Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(
10))";
st.executeUpdate(table);
System.out.println("Table creation process successfully!");
}
catch(SQLException s){
System.out.println("Table all ready exists!");
}
con.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}

Deleting a Table from Database


import java.sql.*;

public class DeleteTable{


public static void main(String[] args) {
System.out.println("Tabel Deletion Example");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement st = con.createStatement();
st.executeUpdate("DROP TABLE Employee1");
System.out.println("Table Deleted successfully!");
}
catch(SQLException s){
System.out.println("Table is not exists!");
}
con.close();
}
catch (Exception e){
e.printStackTrace();
}
}

Inserting values into database tables

import java.sql.*;

public class InsertValues{


public static void main(String[] args) {
System.out.println("Inserting values in Mysql database table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db,"root","root");
try{
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT employee VALUES("+13+","+"'Aman'"+")");
System.out.println("1 row affected");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

Retrieving Rows from a Database Table

import java.sql.*;

public class GetAllRows{


public static void main(String[] args) {
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee6");
System.out.println("Emp_code: " + "\t" + "Emp_name: ");
while (res.next()) {
int i = res.getInt("Emp_code");
String s = res.getString("Emp_name");
System.out.println(i + "\t\t" + s);
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Deleting All Rows from a Database Table
import java.sql.*;

public class DeleteAllRows{


public static void main(String[] args) {
System.out.println
("Example for Deleting All Rows from a database Table!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/jdbctutorial", "root", "root");
try{
Statement st = con.createStatement();
String sql = "DELETE FROM employee6";
int delete = st.executeUpdate(sql);
if(delete == 0){
System.out.println("All rows are completelly deleted!");
}
}
catch(SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

Getting Column Names from a database table in Java

import java.sql.*;

public class ColumnName{


public static void main(String[] args) {
System.out.println("Getting Column Names Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM employee6");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
System.out.println("Number of Column : "+ col);
System.out.println("Columns Name: ");
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
System.out.println(col_name);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

JDBC- Statement

Once a connection is obtained we can interact with the database. The JDBC Statement,
CallableStatement, and PreparedStatement interfaces define the methods and properties that enable us
to send SQL or PL/SQL commands and receive data from our database. They also define methods that
help bridge data type differences between Java and SQL data types used in a database.

Interfaces Description Recommended Use


Use for general-purpose access to
your database. Useful when you are
Execute simple sql queries without
Statement using static SQL statements at
parameters.
runtime. The Statement interface
cannot accept parameters.
Use when you plan to use the SQL
Execute precompiled sql queries statements many times. The
PreparedStatement
with or without parameters. PreparedStatement interface accepts
input parameters at runtime.
Use when you want to access
Execute a call to a database stored database stored procedures. The
CallableStatement
procedure. CallableStatement interface can also
accept runtime input parameters.

A statement object is used to send and execute SQL statements to a database.To execute SQL
statements, instantiate a Statement object from the connection object by using the createStatement()
method.

Statement statement = dbConnection.createStatement();

After creating a Statement object, use it to execute a SQL statement with one of its three execute
methods.

1. boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be
retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when
you need to use truly dynamic SQL.
2. int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the
SQL statement. Use this method to execute SQL statements for which you expect to get a
number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.

3. ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you
expect to get a result set, as you would with a SELECT statement.

For Closing a Statement Object, use stmtObject.close();

The following code segment creates a PreparedStatement object to select user data based on the user's
email address.

PreparedStatement pstmt = con.prepareStatement( select theuser from registration


where emailaddress like ?");
//Initialize first parameter with email address
pstmt.setString(1, emailAddress);
ResultSet results = ps.executeQuery();

An example of a PreparedStatement object used to update a database is shown below.

PreparedStatement pstmt = con.prepareStatement(”update Orders set pname = ? where Prod_Id = ?”);


pstmt.setInt(2, 100);
pstmt.setString(1, “Bob”);
pstmt.executeUpdate();

To close PreparedStatement, use pstmt.close();

Das könnte Ihnen auch gefallen