Lập trình Java - Phần 3

Chia sẻ bởi Nguyễn Bùi Minh Tâm | Ngày 19/03/2024 | 10

Chia sẻ tài liệu: Lập trình Java - Phần 3 thuộc Công nghệ thông tin

Nội dung tài liệu:

11/20/2009
Võ Phương Bình - ITFAC - DLU
1
Part III: GUI Programming & Database Connectivity
Chapter 8: GUI Programming
Chapter 9: Database Connectivity
11/20/2009
Võ Phương Bình - ITFAC - DLU
2
Chapter 8:
GUI Programming
GUI Class Hierarchy
Frames
Creating frames, centering frames, adding components to frames
Layout Managers
FlowLayout, GridLayout, BorderLayout
Drawing on Panels
The paintComponent method
Using Colors, Fonts, and Font Metrics
Drawing Geometric Figures
Lines, Rectangles, Ovals, Arcs, and Polygons
Event-Driven Programming
Event Source, Listener, Listener Interface
11/20/2009
Võ Phương Bình - ITFAC - DLU
3
GUI Class Hierarchy (Swing)
11/20/2009
Võ Phương Bình - ITFAC - DLU
4
JComponent
11/20/2009
Võ Phương Bình - ITFAC - DLU
5
AWT (Optional)
11/20/2009
Võ Phương Bình - ITFAC - DLU
6
Frames
Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications.
The Frame class can be used to create windows.
For Swing GUI programs, use JFrame class to create widows.
11/20/2009
Võ Phương Bình - ITFAC - DLU
7
UI Components
11/20/2009
Võ Phương Bình - ITFAC - DLU
8
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Creating Frames
11/20/2009
Võ Phương Bình - ITFAC - DLU
9
Centering Frames
By default, a frame is displayed in the upper-left corner of the screen.
To display a frame at a specified location, you can use the setLocation(x, y) method in the JFrame class.
This method places the upper-left corner of a frame at location (x, y).
11/20/2009
Võ Phương Bình - ITFAC - DLU
10
Centering Frames, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
11
Adding Components into a Frame
// Add a button into the frame
frame.getContentPane().add(
new JButton("OK"));
11/20/2009
Võ Phương Bình - ITFAC - DLU
12
NOTE
The content pane is a subclass of Container. The statement in the preceding slide can be replaced by the following two lines:
Container container = frame.getContentPane();
container.add(new JButton("OK"));
You may wonder how a Container object is created. It is created when a JFrame object is created. A JFrame object uses the content pane to hold components in the frame.
11/20/2009
Võ Phương Bình - ITFAC - DLU
13
Layout Managers
Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems.
The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container.
11/20/2009
Võ Phương Bình - ITFAC - DLU
14
Kinds of Layout Managers
FlowLayout

GridLayout
BorderLayout
CardLayout
GridBagLayout
11/20/2009
Võ Phương Bình - ITFAC - DLU
15
Example 9.1
Testing the FlowLayout Manager
The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started.
11/20/2009
Võ Phương Bình - ITFAC - DLU
16
FlowLayout Constructors
public FlowLayout(int align, int hGap, int vGap)
Constructs a new FlowLayout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances in
pixel between components.
public FlowLayout(int alignment)
Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical.
public FlowLayout()
Constructs a new FlowLayout with a default
center alignment and a default gap of five pixels
for both horizontal and vertical.
11/20/2009
Võ Phương Bình - ITFAC - DLU
17
Example 9.2
Testing the GridLayout Manager
The GridLayout manager arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor.
The components are placed in the grid from left to right starting with the first row, then the second, and so on.
11/20/2009
Võ Phương Bình - ITFAC - DLU
18
GridLayout Constructors
public GridLayout(int rows,
int columns)
Constructs a new GridLayout with the specified number of rows and columns.
public GridLayout(int rows, int columns, int hGap, int vGap)
Constructs a new GridLayout with the
specified number of rows and columns,
along with specified horizontal and
vertical gaps between components.
11/20/2009
Võ Phương Bình - ITFAC - DLU
19
Example 10.3
Testing the BorderLayout Manager
The BorderLayout manager divides the container into five areas: East, South, West, North, and Center.
Components are added to a BorderLayout by using the add method.
add(Component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER.
11/20/2009
Võ Phương Bình - ITFAC - DLU
20
Example 10.3, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
21
Using Panels as Containers
Panels act as smaller containers for grouping user interface components.
It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel.
11/20/2009
Võ Phương Bình - ITFAC - DLU
22
Example 9.4 Testing Panel
This example uses panels to organize components. The program creates a user interface for a Microwave oven.
11/20/2009
Võ Phương Bình - ITFAC - DLU
23
Drawing on Panels
JPanel can be used to draw graphics (including text) and enable user interaction.
To draw in a panel, you create a new class that extends JPanel and override the paintComponent method to tell the panel how to draw things.
You can then display strings, draw geometric shapes, and view images on the panel.
11/20/2009
Võ Phương Bình - ITFAC - DLU
24
Drawing on Panels, cont.
public class DrawMessage extends JPanel {
/** Main method */
public static void main(String[] args) {
JFrame frame = new JFrame("DrawMessage");
frame.getContentPane().add(new DrawMessage());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setVisible(true);
}
 
/** Paint the message */
public void paintComponent(Graphics g) {
super.paintComponent(g);
 
g.drawString("Welcome to Java!", 40, 40);
}
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
25
Drawing on Panels, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
26
NOTE
The Graphics class is an abstract class for displaying figures and images on the screen on different platforms.
The Graphics class is implemented on the native platform in the JVM.
When you use the paintComponent method to draw things on a graphics context g, this g is an instance of a concrete subclass of the abstract Graphics class for the specific platform.
The Graphics class encapsulates the platform details and enables you to draw things uniformly without concerning specific platforms.
11/20/2009
Võ Phương Bình - ITFAC - DLU
27
NOTE
Whenever a component is displayed, a Graphics object is created for the component.
The Swing components use the paintComponent method to draw things.
The paintComponent method is automatically invoked to paint the graphics context when the component is first displayed or whenever the component needs to be redisplayed.
Invoking super.paintComponent(g) is necessary to ensure that the viewing area is cleared before a new drawing is displayed.
11/20/2009
Võ Phương Bình - ITFAC - DLU
28
NOTE
To draw things, normally you create a subclass of JPanel and override its paintComponent method to tell the system how to draw.
In fact, you can draw things on any GUI component.
11/20/2009
Võ Phương Bình - ITFAC - DLU
29
The Color Class
You can set colors for GUI components by using the java.awt.Color class.
Colors are made of red, green, and blue components, each of which is represented by a byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model.
Color c = new Color(r, g, b);
r, g, and b specify a color by its red, green, and blue components.
Example:
Color c = new Color(228, 100, 255);
11/20/2009
Võ Phương Bình - ITFAC - DLU
30
Setting Colors
You can use the following methods to set the component’s background and foreground colors:
setBackground(Color c)
setForeground(Color c)
Example:
setBackground(Color.yellow); setForeground(Color.red);
11/20/2009
Võ Phương Bình - ITFAC - DLU
31
The Font Class
Font myFont = Font(name, style, size);
Example:
Font myFont = new Font("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);
11/20/2009
Võ Phương Bình - ITFAC - DLU
32
Finding All Available Font Names
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
11/20/2009
Võ Phương Bình - ITFAC - DLU
33
Setting Fonts
public void paint(Graphics g) {
Font myFont = new Font("Times", Font.BOLD, 16);
g.setFont(myFont);
g.drawString("Welcome to Java", 20, 40);

//set a new font
g.setFont(new Font("Courier", Font.BOLD+Font.ITALIC, 12));
g.drawString("Welcome to Java", 20, 70);
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
34
The FontMetrics Class
public void paint(Graphics g) {
g.getFontMetrics(Font f); or
g.getFontMetrics();
}
11/20/2009
Võ Phương Bình - ITFAC - DLU
35
Get FontMetrics
public int getAscent()
public int getDescent()
public int getLeading()
public int getHeight()
public int stringWidth(String str)
11/20/2009
Võ Phương Bình - ITFAC - DLU
36
Example 9.5
Using FontMetrics
Objective: Display “Welcome to Java” in SansSerif 20-point bold, centered in the frame.
11/20/2009
Võ Phương Bình - ITFAC - DLU
37
11/20/2009
Võ Phương Bình - ITFAC - DLU
38
Example 9.6, cont.
11/20/2009
Võ Phương Bình - ITFAC - DLU
39
Drawing Geometric Figures
Drawing Lines
Drawing Rectangles
Drawing Ovals
Drawing Arcs
Drawing Polygons
11/20/2009
Võ Phương Bình - ITFAC - DLU
40
Drawing Lines
drawLine(x1, y1, x2, y2);
11/20/2009
Võ Phương Bình - ITFAC - DLU
41
Drawing Rectangles
drawRect(x, y, w, h);
fillRect(x, y, w, h);
11/20/2009
Võ Phương Bình - ITFAC - DLU
42
Drawing Rounded Rectangles
drawRoundRect(x, y, w, h, aw, ah);
fillRoundRect(x, y, w, h, aw, ah);
11/20/2009
Võ Phương Bình - ITFAC - DLU
43
Drawing Ovals
drawOval(x, y, w, h);
fillOval(x, y, w, h);
11/20/2009
Võ Phương Bình - ITFAC - DLU
44
Drawing Arcs
drawArc(x, y, w, h, angle1, angle2);
fillArc(x, y, w, h, angle1, angle2);
11/20/2009
Võ Phương Bình - ITFAC - DLU
45
Drawing Polygons
int[] x = {40, 70, 60, 45, 20};
int[] y = {20, 40, 80, 45, 60};
g.drawPolygon(x, y, x.length);
g.fillPolygon(x, y, x.length);
11/20/2009
Võ Phương Bình - ITFAC - DLU
46
Example 9.7
Drawing a Clock
Objective: Use drawing and trigonometric methods to draw a clock showing the specified hour, minute, and second in a frame.
11/20/2009
Võ Phương Bình - ITFAC - DLU
47
Drawing Clock
xEnd = xCenter + handLength  sin()
yEnd = yCenter - handLength  cos()
Since there are sixty seconds in one minute, the angle for the second hand is
second  (2/60)
11/20/2009
Võ Phương Bình - ITFAC - DLU
48
Drawing Clock, cont.
xEnd = xCenter + handLength  sin()
yEnd = yCenter - handLength  cos()
The position of the minute hand is determined by the minute and second.
The exact minute value comined with seconds is minute + second/60.
For example, if the time is 3 minutes and 30 seconds. The total minutes are 3.5. Since there are sixty minutes in one hour, the angle for the minute hand is
(minute + second/60)  (2/60)
11/20/2009
Võ Phương Bình - ITFAC - DLU
49
Drawing Clock, cont.
xEnd = xCenter + handLength  sin()
yEnd = yCenter - handLength  cos()
Since one circle is divided into twelve hours, the angle for the hour hand is
(hour + minute/60 + second/(60  60)))  (2/12)
11/20/2009
Võ Phương Bình - ITFAC - DLU
50
Event-Driven Programming
Procedural programming is executed in procedural order.
In event-driven programming, code is executed upon activation of events.
11/20/2009
Võ Phương Bình - ITFAC - DLU
51
Events
An event can be defined as a type of signal to the program that something has happened.
The event is generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer.
11/20/2009
Võ Phương Bình - ITFAC - DLU
52
Event Information
id: A number that identifies the event.
target: The source component upon which the event occurred.
arg: Additional information about the source components.
x, y coordinates: The mouse pointer location when a mouse movement event occurred.
clickCount: The number of consecutive clicks for the
mouse events. For other events, it is zero.
when: The time stamp of the event.
key: The key that was pressed or released.
11/20/2009
Võ Phương Bình - ITFAC - DLU
53
Event Classes
11/20/2009
Võ Phương Bình - ITFAC - DLU
54
Selected User Actions
Source Event Type
User Action Object Generated
Clicked on a button JButton ActionEvent
Changed text JTextComponent TextEvent
Double-clicked on a list item JList ActionEvent
Selected or deselected an item JList ItemEvent
with a single click
Selected or deselected an item JComboBox ItemEvent
11/20/2009
Võ Phương Bình - ITFAC - DLU
55
The Delegation Model
11/20/2009
Võ Phương Bình - ITFAC - DLU
56
Selected Event Handlers
Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
WindowEvent WindowListener windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
ContainerEvent ContainerListener
componentAdded(ContainerEvent) componentRemoved(ContainerEvent)
11/20/2009
Võ Phương Bình - ITFAC - DLU
57
Example 9.8
Handling Simple Action Events
Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked.
11/20/2009
Võ Phương Bình - ITFAC - DLU
58
Example 9.9
Handling Window Events
Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.
11/20/2009
Võ Phương Bình - ITFAC - DLU
59
Example 9.9 Multiple Listeners for a Single Source
TestMultipleListener
Run
Objective: This example modifies Example 10.7 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listener. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.
11/20/2009
Võ Phương Bình - ITFAC - DLU
60
Chapter 9: Database Connectivity
ODBC
JDBC
11/20/2009
Võ Phương Bình - ITFAC - DLU
61
What is ODBC?
ODBC is (Open Database Connectivity):
A standard or open application programming interface (API) for accessing a database.
SQL Access Group, chiefly Microsoft, in 1992
By using ODBC statements in a program, you can access files in a number of different databases, including Access, dBase, DB2, Excel, and Text.
It allows programs to use SQL requests that will access databases without having to know the proprietary interfaces to the databases.
ODBC handles the SQL request and converts it into a request the individual database system understands.
11/20/2009
Võ Phương Bình - ITFAC - DLU
62
More on ODBC
You need:
the ODBC software, and
a separate module or driver for each database to be accessed. Library that is dynamically connected to the application.
Driver masks the heterogeneity of DBMS operating system and network protocol.
E.g. (Sybase, Windows/NT, Novell driver)
11/20/2009
Võ Phương Bình - ITFAC - DLU
63
ODBC Architecture
Application
ODBC driver
manager
Driver
(DBMS/OS/network)
Data Source
11/20/2009
Võ Phương Bình - ITFAC - DLU
64
What is JDBC?
JDBC is: Java Database Connectivity
is a Java API for connecting programs written in Java to the data in relational databases.
consists of a set of classes and interfaces written in the Java programming language.
provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API.
The standard defined by Sun Microsystems, allowing individual providers to implement and extend the standard with their own JDBC drivers.
JDBC:
establishes a connection with a database
sends SQL statements
processes the results.
11/20/2009
Võ Phương Bình - ITFAC - DLU
65
JDBC and ODBC
ODBC is used between applications
JDBC is used by Java programmers to connect to databases
With a small "bridge" program, you can use the JDBC interface to access ODBC-accessible databases.
JDBC allows SQL-based database access for EJB persistence and for direct manipulation from CORBA, DJB or other server objects
11/20/2009
Võ Phương Bình - ITFAC - DLU
66
JDBC API
The JDBC API supports both two-tier and three-tier models for database access.
Two-tier model -- a Java applet or application interacts directly with the database.
Three-tier model -- introduces a middle-level server for execution of business logic:
the middle tier to maintain control over data access.
the user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls.
11/20/2009
Võ Phương Bình - ITFAC - DLU
67
JDBC Architectures
11/20/2009
Võ Phương Bình - ITFAC - DLU
68
The JDBC Steps
1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set Object
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection
11/20/2009
Võ Phương Bình - ITFAC - DLU
69
1. Importing Packages
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
11/20/2009
Võ Phương Bình - ITFAC - DLU
70
2. Registering JDBC Drivers
Class.forName(DBDriver);
DBDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
11/20/2009
Võ Phương Bình - ITFAC - DLU
71
3: Opening connection to a Database
DriverManager.getConnection(DBSource,sqlUser,sqlPass);
DBSource = "jdbc:odbc:NorthWind";
sqlUser = "sa";
sqlPass = "sa";
Return a Connection object.
Connection myConnection;
myConnection = DriverManager.getConnection(DBSource,sqlUser,sqlPass);
11/20/2009
Võ Phương Bình - ITFAC - DLU
72
4. Creating a Statement Object
Call createStatement() method:
myConnection.createStatement();
Return a Statement object:
Statement stmt;
stmt = myConnection.createStatement();
11/20/2009
Võ Phương Bình - ITFAC - DLU
73
5. Executing a Query, Returning a Result Set Object
6. Processing the Result Set
ResultSet rs;
ResultSetMetaData rsmd;
rs = stmt.executeQuery(strSQL);
rsmd = rs.getMetaData();
int col = rsmd.getColumnCount();
while(rs.next()){
for(int i=1; i<=col; i++){
System.out.print(rs.getString(i)+ " ");
}
System.out.println();
11/20/2009
Võ Phương Bình - ITFAC - DLU
74
7. Closing the Result Set and Statement Objects
8. Closing the Connection
rs.close();
stmt.close();
myConnection.close();


11/20/2009
Võ Phương Bình - ITFAC - DLU
75
Update Query
With a strSQL update string:
Example strSQL = “Insert Into Table Values(val1, val2, …)”;
stmt.executeUpdate(strSQL);
Use StoreProcedure:
Replace strSQL by StoreProcedure

* Một số tài liệu cũ có thể bị lỗi font khi hiển thị do dùng bộ mã không phải Unikey ...

Người chia sẻ: Nguyễn Bùi Minh Tâm
Dung lượng: | Lượt tài: 0
Loại file:
Nguồn : Chưa rõ
(Tài liệu chưa được thẩm định)