¿Tienes una cuenta? identificate: Usuario Contraseña o puedes obtener una gratis.

[ Escribo sobre... ]

Manual Java 2da. parte

mié 06 de abril, 2005 - 16:40

Estado de ánimo: X
Seguridad de entrada: PUBLICO

Example 53 Nested for loops
This program prints a four-line triangle of asterisks (*):
for (int i=1; i==4; i++) {
for (int j=1; j==i; j++)
System.out.print(”*”);
System.out.println();
}
Example 54 Array search using while loop
This method behaves the same as wdayno1 in Example 51:
static int wdayno2(String wday) {
int i=0;
while (i = wdays.length && ! wday.equals(wdays[i]))
i++;
// Now i >= wdays.length or wday equal to wdays[i]
if (i = wdays.length)
return i+1;
else
return -1; // Here used to mean ‘not found’
}
static final String[] wdays =
{ “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday” };
Example 55 Infinite loop because of misplaced semicolon
Here a misplaced semicolon (;) creates an empty loop body statement, where the increment i++ is
not part of the loop. Hence it will not terminate, but loop forever:
int i=0;
while (i=10);
i++;
Example 56 Using do-while (but while is usually preferable)
Throw a die and compute sum until 5 or 6 comes up:
static int waitsum() {
int sum = 0, eyes;
do {
eyes = (int)(1 + 6 * Math.random());
sum += eyes;
} while (eyes = 5);
return sum;
}
46 Statements
12.6 Labelled statements, returns, exits and exceptions
12.6.1 The return statement
The simplest form of a return statement, without an expression argument, is:
return;
That form of return statement must occur inside the body of a method whose returntype is void, or
inside the body of a constructor. Execution of the return statement exits the method or constructor,
and continues execution at the place from which it was called.
Alternatively, a return statement may have an expression argument:
return expression;
That form of return statement must occur inside the body of a method (not constructor) whose
returntype is a supertype of the type of the expression. The return statement is executed as follows:
First the expression is evaluated to some value v. Then it exits the method, and continues execution
at the method call expression that called the method; the value of that expression will be v.
12.6.2 The labelled statement
A labelled statement has the form
label : statement
where label is an identifier. The scope of label is statement, where it can be used in connection with
break (Section 12.6.3) and continue (Section 12.6.4). It is illegal to re-use the same label inside
statement, unless inside a local class in statement.
12.6.3 The break statement
A break statement is legal only inside a switch or loop, and has one of the forms
break;
break label;
Executing break exits the inner-most enclosing switch or loop, and continues execution after that
switch or loop. Executing break label exits that enclosing statement which has label label, and
continues execution after that statement. Such a statement must exist in the inner-most enclosing
method or constructor or initializer block.
12.6.4 The continue statement
A continue statement is legal only inside a loop, and has one of the forms
continue;
continue label;
Executing continue terminates the current iteration of the inner-most enclosing loop, and continues
the execution at the step (in for loops; see Section 12.5.1), or the condition (in while and do-while
loops; see Sections 12.5.2 and 12.5.3). Executing continue label terminates the current iteration of
that enclosing loop which has label label, and continues the execution at the step or the condition.
There must be such a loop in the inner-most enclosing method or constructor or initializer block.
Statements 47
Example 57 Using return to terminate a loop early
This method behaves the same as wdayno2 in Example 54:
static int wdayno3(String wday) {
for (int i=0; i = wdays.length; i++)
if (wday.equals(wdays[i]))
return i+1;
return -1; // Here used to mean ‘not found’
}
Example 58 Using break to terminate a loop early
double prod = 1.0;
for (int i=0; i=xs.length; i++) {
prod *= xs[i];
if (prod 0.0) break; } Example 59 Using continue to start a new iteration This method decides whether query is a substring of target. When a mismatch between the strings is found, continue starts the next iteration of the outer for loop, thus incrementing j: static boolean substring1(String query, String target) { nextposition: for (int j=0; jtarget.length()-query.length(); j++) {
for (int k=0; k=query.length(); k++)
if (target.charAt(j+k) != query.charAt(k))
continue nextposition;
return true;
}
return false;
}
Example 60 Using break to exit a labelled statement block
This method behaves as substring1 from Example 59. It uses break to exit the entire statement
block labelled thisposition, thus skipping the first return statement and starting a new iteration
of the outer for loop:
static boolean substring2(String query, String target) {
for (int j=0; j==target.length()-query.length(); j++)
thisposition: {
for (int k=0; k=query.length(); k++)
if (target.charAt(j+k) != query.charAt(k))
break thisposition;
return true;
}
return false;
}
48 Statements
12.6.5 The throw statement
A throw statement has the form
throw expression;
where the type of expression must be a subtype of class Throwable (Section 14). The throw statement
is executed as follows: The expression is evaluated to obtain an exception object v. If it is
null, then the exception NullPointerException is thrown. Otherwise, the exception object v is
thrown. In any case, the enclosing block statement is terminated abnormally; see Section 14. The
thrown exception may be caught in a dynamically enclosing try-catch statement (Section 12.6.6).
If the exception is not caught, then the entire program execution will be aborted, and information
from the exception will be printed on the console (for example, at the command prompt, or in the
Java Console inside a web browser).
12.6.6 The try-catch-finally statement
A try-catch statement is used to catch (particular) exceptions thrown by the execution of a block
of code. It has the following form:
try
body
catch (E1 ×1) catchbody1
catch (E2 ×2) catchbody2
...
finally finallybody
where E1, E2, . . . are names of exception types, the x1, x2, . . . are variable names, and the body,
the catchbodyi and the finallybody are block-statements (Section 12.2). There can be zero or more
catch blocks, and the finally clause may be absent, but at least one catch or finally clause
must be present.
We say that Ei matches exception type E if E is a subtype of Ei (possibly equal to Ei).
The try-catch-finally statement is executed by executing the body. If the execution of body
terminates normally, or exits by return or break or continue (when inside a method or constructor
or switch or loop), then the catch blocks are ignored. If body terminates abnormally by throwing
exception e of class E, then the first matching Ei (if any) is located, variable xi is bound to e, and
the corresponding catchbodyi is executed. If there is no matching Ei, then the entire try-catch
statement terminates abnormally with exception e.
If a finally clause is present, then the finallybody will be executed regardless whether the
execution of body terminated normally, regardless whether body exited by executing return or
break or continue (when inside a method or constructor or switch or loop), regardless whether
any exception thrown by body was caught by the catch blocks, and regardless whether any new
exception was thrown during the execution of a catch body.
Statements 49
Example 61 Throwing an exception to indicate failure
Instead of returning the bogus error value -1 as in method wdayno3 above, throw an exception of
class WeekdayException (Example 67). Note the throws clause (Section 9.8) in the method header:
static int wdayno4(String wday) throws WeekdayException {
for (int i=0; i = wdays.length; i++)
if (wday.equals(wdays[i]))
return i+1;
throw new WeekdayException(wday);
}
Example 62 A try-catch block
This example calls the method wdayno4 (Example 61) inside a try-catch block that handles exceptions
of class WeekdayException (Example 67) and its superclass Exception. The second catch
clause will be executed (for example) if the array access args0 fails because there is no command
line argument (since ArrayIndexOutOfBoundsException is a subclass of Exception). If an exception
is handled, it is bound to the variable x, and printed by an implicit call (Section 7) to the
exception’s toString-method:
public static void main(String[] args) {
try {
System.out.println(args0 + “ is weekday number “ + wdayno4(args0));
} catch (WeekdayException x) {
System.out.println(“Weekday problem: “ + x);
} catch (Exception x) {
System.out.println(“Other problem: “ + x);
}
}
Example 63 A try-finally block
This method attempts to read three lines from a file, each containing a single floating-point number.
Regardless whether anything goes wrong during reading (premature end of file, ill-formed number),
the finally clause will close the readers before the method returns. It would do so even if the
return statement were inside the try block:
static double[] readRecord(String filename) throws IOException {
Reader freader = new FileReader(filename);
BufferedReader breader = new BufferedReader(freader);
double[] res = new double3;
try {
res0 = new Double(breader.readLine()).doubleValue();
res1 = new Double(breader.readLine()).doubleValue();
res2 = new Double(breader.readLine()).doubleValue();
} finally {
breader.close();
freader.close();
}
return res;
}
50 Interfaces
13 Interfaces
13.1 Interface declarations
An interface describes fields and methods, but does not implement them. An interface-declaration
may contain field descriptions, method descriptions, class declarations, and interface declarations.
The declarations in an interface may appear in any order:
interface-modifiers interface I extends-clause {
field-descriptions
method-descriptions
class-declarations
interface-declarations
}
An interface may be declared at top-level or inside a class or interface, but not inside a method or
constructor or initializer. At top-level, the interface-modifiers may be public, or absent. A public
interface is accessible also outside its package. Inside a class or interface, the interface-modifiers
may be static (always implicitly understood), and at most one of public, protected, or private.
The extends-clause may be absent or have the form
extends I1, I2, ...
where I1, I2, . . . are interface names. If the extends-clause is present, then interface I describes all
those members described by I1, I2, . . . , and interface I is a subinterface (and hence subtype) of
I1, I2, . . . . Interface I can describe additional fields and methods, but cannot override inherited
member descriptions.
A field-description in an interface declares a named constant, and must have the form
field-desc-modifiers type f = initializer;
where field-desc-modifiers is a list of static, final, and public; all of which are understood and
need not be given explicitly. The field initializer must be an expression involving only literals and
operators, and static members of classes and interfaces.
A method-description for method m must have the form:
method-desc-modifiers returntype m(formal-list) throws-clause;
where method-desc-modifiers is a list of abstract and public, both of which are understood and
need not be given explicitly.
A class-declaration inside an interface is always implicitly static and public.
13.2 Classes implementing interfaces
A class C may be declared to implement one or more interfaces by an implements-clause:
class C implements I1, I2, ...
classbody
In this case, C is a subtype (see Section 5.4) of I1, I2, and so on. The compiler will check that C
declares all the methods described by I1, I2, . . . , with exactly the prescribed signatures and return
types. A class may implement any number of interfaces. Fields, classes, and interfaces declared in
I1, I2, . . . can be used in class C.
Interfaces 51
Example 64 Three interface declarations
import java.awt.*;
interface Colored { Color getColor(); }
interface Drawable { void draw(Graphics g); }
interface ColoredDrawable extends Colored, Drawable {}
Example 65 Classes implementing interfaces
Note that the methods getColor and draw must be public because they are implicitly public in the
above interfaces.
class ColoredPoint extends Point implements Colored {
Color c;
ColoredPoint(int x, int y, Color c) { super(x, y); this.c = c; }
public Color getColor() { return c; }
}
class ColoredDrawablePoint extends ColoredPoint implements ColoredDrawable {
Color c;
ColoredDrawablePoint(int x, int y, Color c) { super(x, y, c); }
public void draw(Graphics g) { g.fillRect(x, y, 1, 1); }
}
class ColoredRectangle implements ColoredDrawable {
int x1, x2, y1, y2; // (x1, y1) upper left, (x2, y2) lower right corner
Color c;
ColoredRectangle(int x1, int y1, int x2, int y2, Color c)
{ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.c = c; }
public Color getColor() { return c; }
public void draw(Graphics g) { g.drawRect(x1, y1, x2-x1, y2-y1); }
}
Example 66 Using interfaces as types
static void printcolors(Colored[] cs) {
for (int i=0; i=cs.length; i++)
System.out.println(cs[i].getColor().toString());
}
static void draw(Graphics g, ColoredDrawable[] cs) {
for (int i=0; i=cs.length; i++) {
g.setColor(cs[i].getColor());
cs[i].draw(g);
}
}
52 Exceptions
14 Exceptions
An exception is an object of an exception type: a subclass of class Throwable. An exception is
used to signal and describe an abnormal situation during program execution. The evaluation of an
expression or the execution of a statement may terminate abnormally by throwing an exception,
either by executing a throw statement (Section 12.6.5) or by executing a primitive operation, such
as assignment to an array element, that may throw an exception.
A thrown exception may be caught in a dynamically enclosing try-catch statement (Section
12.6.6). A caught exception may be re-thrown by a throw statement. If the exception is not
caught, then the entire program execution will be aborted, and information from the exception will
be printed on the console (for example, at the command prompt, or in the Java Console inside a web
browser). What is printed on the console is determined by the exception’s toString method.
Checked and unchecked exception types
There are two kinds of exception types: checked (those that must be declared in the throws-clause
of a method or constructor; Section 9.8) and unchecked (those that need not). If the execution of
a method body can throw a checked exception of class E, then class E or a supertype of E must be
declared in the throws-clause of the method.
Some of the most important predefined exception types, and their status (checked or unchecked)
are shown below.
Throwable
Error unchecked
ExceptionInInitializerError |
OutOfMemoryError |
StackOverflowError |
Exception checked
InterruptedException |
IOException |
RuntimeException unchecked
ArithmeticException |
ArrayStoreException |
ClassCastException |
IllegalMonitorStateException |
IndexOutOfBoundsException |
ArrayIndexOutOfBoundsException |
StringIndexOutOfBoundsException |
NullPointerException |
Exceptions 53
Example 67 Declaring a checked exception class
This is the class of exceptions thrown by method wdayno4 (Example 61). Note the toString method
which is used when printing an uncaught exception on the console:
class WeekdayException extends Exception {
private String wday;
public WeekdayException(String wday)
{ this.wday = wday; }
public String toString()
{ return “Illegal weekday “ + wday; }
}
54 Threads, concurrent execution, and synchronization
15 Threads, concurrent execution, and synchronization
15.1 Threads and concurrent execution
The preceding chapters describe sequential program execution, in which expressions are evaluated
and statements are executed one after the other: we have considered only a single thread of execution,
where a thread is an independent sequential activity. A Java program may execute several threads
concurrently, that is, potentially overlapping in time. For instance, one part of a program may
continue computing while another part is blocked waiting for input; see Example 68.
Threads are created and manipulated using the Thread class and the Runnable interface, both
of which are part of the Java class library package java.lang.
To program a new thread, one must implement the method public void run() described by the
Runnable interface. One can do this by declaring a subclass U of class Thread (which implements
Runnable). To create a new thread, create an object u of class U, and to permit it to run, execute
u.start(). This enables the new thread, so that it can execute concurrently with the current thread;
see Example 68.
Alternatively, declare a class C that implements Runnable, create an object o of that class, create
a thread object u = new Thread(o) from o, and execute u.start(); see Example 72.
Threads can communicate with each other only via shared state, namely, by using and assigning
static fields, non-static fields, and array elements. By the design of Java, threads cannot use local
variables and method parameters for communication.
States and state transitions of a thread
A thread is alive if it has been started and has not died. A thread dies by exiting its run() method,
either by returning or by throwing an exception. A live thread is in one of the states Enabled (ready
to run), Running (actually executing), Sleeping (waiting for a timeout), Joining (waiting for another
thread to die), Locking (trying to get the lock on object o), or Waiting (for notification on object o).
The state transitions of a thread can be summarized by this table and the figure opposite:
From state To state Reason for the transition
Enabled Running the system schedules the thread for execution
Running Enabled the system preempts the thread and schedules another
Enabled the thread executes yield()
Waiting the thread executes o.wait(), thus releasing the lock on o
Locking the thread attempts to execute synchronized (o) { ... }
Sleeping the thread executes sleep()
Joining the thread executes u.join()
Running the thread was interrupted; sets the interrupted status of the thread
Dead the thread exited run() by returning or by throwing an exception
Sleeping Enabled the sleeping period expired
Enabled the thread was interrupted; throws InterruptedException when run
Joining Enabled the thread u being joined died, or the join timed out
Enabled the thread was interrupted; throws InterruptedException when run
Waiting Locking another thread executed o.notify() or o.notifyAll()
Locking the wait for the lock on o timed out
Locking the thread was interrupted; throws InterruptedException when run
Locking Enabled the lock on o became available and was given to this thread
Threads, concurrent execution, and synchronization 55
Example 68 Multiple threads
The main program creates a new thread, binds it to u, and starts it. Now two threads are executing
concurrently: one executes main, and another executes run. While the main method is blocked
waiting for keyboard input, the new thread keeps incrementing i. The new thread executes yield()
to make sure that the other thread is allowed to run (when not blocked).
class Incrementer extends Thread {
public int i;
public void run() {
for (;;) { // Forever
i++; // increment i
yield();
}
} }
class ThreadDemo {
public static void main(String[] args) throws IOException {
Incrementer u = new Incrementer();
u.start();
System.out.println(“Repeatedly press Enter to get the current value of i:”);
for (;;) {
System.in.read(); // Wait for keyboard input
System.out.println(u.i);
} } }
The states and state transitions of a thread
A thread’s transition from one state to another may be caused by a method call performed by the
thread itself (shown in the typewriter font), by a method call possibly performed by another thread
(shown in the slanted font); and by timeouts and other actions (shown in the default font):
Enabled Running
Locking o Waiting for o
interrupt()
timeout
o.notifyAll() o.notify()
Sleeping Dead Created
Joining u
got lock
on o attempting to lock o o.wait()
scheduled
preempted
yield()
u.join()
sleep()
interrupt()
timeout
timeout
interrupt() u died
start() dies
56 Threads, concurrent execution, and synchronization
15.2 Locks and the synchronized statement
When multiple concurrent threads access the same fields or array elements, there is considerable risk
of creating an inconsistent state; see Example 70. To avoid this, threads may synchronize the access
to shared state, such as objects and arrays. A single lock is associated with every object, array, and
class. A lock can be held by at most one thread at a time.
A thread may explicitly ask for the lock on an object or array by executing a synchronized
statement, which has this form:
synchronized (expression)
block-statement
The expression must have reference type. The expression must evaluate to a non-null reference
o; otherwise a NullPointerException is thrown. After the evaluation of the expression, the
thread becomes Locking on object o; see the figure on page 55. When the thread obtains the lock on
object o (if ever), the thread becomes Enabled, and may become Running so the block-statement is
executed. When the block-statement terminates or is exited by return or break or continue or by
throwing an exception, then the lock on o is released.
A synchronized non-static method declaration (Section 9.8) is a shorthand for a method whose
body has the form:
synchronized (this)
method-body
That is, the thread will execute the method body only when it has obtained the lock on the current
object. It will hold the lock until it leaves the method body, and release it at that time.
A synchronized static method declaration (Section 9.8) in class C is a shorthand for a method
whose body has the form:
synchronized (C.class)
method-body
That is, the thread will execute the method body only when it has obtained the lock on the object
C.class, which is the unique object of class Class associated with the class C. It will hold the lock
until it leaves the method body, and release it at that time.
Constructors and initializers cannot be synchronized.
Mutual exclusion is ensured only if all threads accessing a shared object lock it before use. For
instance, if we add an unsynchronized method roguetransfer to a bank object (Example 70), we
can no longer be sure that a thread calling the synchronized method transfer has exclusive access
to the bank object: any number of threads could be executing roguetransfer at the same time.
A monitor is an object whose fields are private and are manipulated only by synchronized methods
of the object, so that all field access is subject to synchronization; see Example 71.
If a thread u needs to wait for some condition to become true, or for a resource to become available,
it may release its lock on object o by calling o.wait(). The thread must own the lock on object
o, otherwise exception IllegalMonitorStateException is thrown. The thread u will be added to
a set of threads waiting for notification on object o. This notification must come from another thread
which has obtained the lock on o and which executes o.notify() or o.notifyAll(). The notifying
thread does not lose the lock on o. After being notified, u must obtain the lock on o again before
it can proceed. Thus when the call to wait returns, thread u will own the lock on o just as before the
call; see Example 71.
For detailed rules governing the behaviour of unsynchronized Java threads, see the Java Language Specification,
Chapter 17.
Threads, concurrent execution, and synchronization 57
Example 69 Mutual exclusion
A Printer thread forever prints a (-) followed by a (/). If we create and run two concurrent printer
threads using new Printer().start() and new Printer().start(), then only one of the threads
can hold the lock on object mutex at a time, so no other symbols can be printed between (-) and
(/) in one iteration of the for loop. Thus the program must print //-/-/-/-/-/ and so on.
However, if the synchronization is removed, it may print —//—/-/-//—// and so on. (The call
pause(n) pauses the thread for 200 ms, whereas pause(100,300) pauses between 100 and 300
ms. This is done only to make the inherent non-determinacy of unsynchronized concurrency more
easily observable).
class Printer extends Thread {
static Object mutex = new Object();
public void run() {
for (;;) {
synchronized (mutex) {
System.out.print(”-”);
Util.pause(100,300);
System.out.print(”/”);
}
Util.pause(200);
} } }
Example 70 Synchronized methods in an object
The bank object below has two accounts. Money is repeatedly being transferred from one account
to the other by clerks. Clearly the total amount of money should remain constant (at 30 euro). This
holds true when the transfer method is declared synchronized, because only one clerk can access the
accounts at any one time. If the synchronized declaration is removed, the sum will differ from 30
most of the time, because one clerk is likely to overwrite the other’s deposits and withdrawals .
class Bank {
private int account1 = 10, account2 = 20;
synchronized public void transfer(int amount) {
int new1 = account1 – amount;
Util.pause(10);
account1 = new1; account2 = account2 + amount;
System.out.println(“Sum is “ + (account1+account2));
} }
class Clerk extends Thread {
private Bank bank;
public Clerk(Bank bank) { this.bank = bank; }
public void run() {
for (;;) { // Forever
bank.transfer(Util.random(-10, 10)); // transfer money
Util.pause(200, 300); // then take a break
} } }
... Bank bank = new Bank();
... new Clerk(bank).start(); new Clerk(bank).start();
58 Threads, concurrent execution, and synchronization
15.3 Operations on threads
The current thread, whose state is Running, may call these methods among others. Further Thread
methods are described in the Thread section of the Java class library; see Section 18.
_
Thread.yield() changes the state of the current thread from Running to Enabled, and thereby
allows the system to schedule another Enabled thread, if any.
_
Thread.sleep(n) sleeps for n milliseconds: the current thread becomes Sleeping, and after
n milliseconds becomes Enabled. May throw InterruptedException if the thread is
interrupted while sleeping.
_
Thread.currentThread() returns the current thread object.
_
Thread.interrupted() returns and clears the interrupted status of the current thread: true
if it has been interrupted since the last call to Thread.interrupted(); otherwise false.
Let u be a thread (an object of a subclass of Thread). Then
_
u.start() changes the state of u to Enabled, so that its run method will be called when a
processor becomes available.
_
u.interrupt() interrupts the thread u: if u is Running or Enabled or Locking, then its interrupted
status is set to true. If u is Sleeping or Joining it will become Enabled, and if it is
Waiting it will become Locking; in these cases u will throw InterruptedException when
and if it becomes Running.
_
u.isInterrupted() returns the interrupted status of u (and does not clear it).
_
u.join() waits for thread u to die; may throw InterruptedException if the current thread
is interrupted while waiting.
_
u.join(n) works as u.join() but times out and returns after at most n milliseconds. There
is no indication whether the call returned because of a timeout or because u died.
Operations on locked objects
A thread which owns the lock on an object o may call the following methods, inherited by o from
class Object in the Java class library; see Section 18.
_
o.wait() releases the lock on o, changes its own state to Waiting, and adds itself to the
set of threads waiting for notification about o. When notified (if ever), the thread must obtain
the lock on o, so when the call to wait returns, it again has the lock on o. May throw
InterruptedException if the thread is interrupted while waiting.
_
o.wait(n) works as o.wait() except that the thread will change state to Locking after n milliseconds,
regardless whether there has been a notification on o or not. There is no indication
whether the state change was caused by a timeout or because of a notification.
_
o.notify() chooses an arbitrary thread among the threads waiting for notification about o (if
any), and changes its state to Locking. The chosen thread cannot actually get the lock on o
until the current thread has released it.
_
o.notifyAll() works as o.notify(), except that it changes the state to Locking for all
threads waiting for notification about o.
Threads, concurrent execution, and synchronization 59
Example 71 Producers and consumers communicating via a monitor
A Buffer has room for one integer, and has a method put for storing into the buffer (if empty) and
a method get for reading from the buffer (if non-empty); it is a monitor (page 56). A thread calling
get must obtain the lock on the buffer. If it finds that the buffer is empty, it calls wait to (release
the lock and) wait until something has been put into the buffer. If another thread calls put and thus
notify, then the getting thread will start competing for the buffer lock again, and if it gets it, will
continue executing. Here we have used a synchronized statement in the method body (instead of
making the method synchronized, as is normal for a monitor) to emphasize that synchronization,
wait and notify all work on the buffer object this:
class Buffer {
private int contents;
private boolean empty = true;
public int get() {
synchronized (this) {
while (empty)
try { this.wait(); } catch (InterruptedException x) {};
empty = true;
this.notify();
return contents;
} }
public void put(int v) {
synchronized (this) {
while (!empty)
try { this.wait(); } catch (InterruptedException x) {};
empty = false;
contents = v;
this.notify();
} }
}
Example 72 Graphic animation using the Runnable interface
Class AnimatedCanvas below is a subclass of Canvas, and so cannot be a subclass of Thread also.
Instead it declares a run method and implements the Runnable interface. The constructor creates a
Thread object u from the AnimatedCanvas object this, and then starts the thread. The new thread
executes the run method, which repeatedly sleeps and repaints, thus creating an animation.
class AnimatedCanvas extends Canvas implements Runnable {
AnimatedCanvas() { Thread u = new Thread(this); u.start(); }
public void run() { // from Runnable
for (;;) { // forever sleep and repaint
try { Thread.sleep(100); } catch (InterruptedException e) { }
...
repaint();
}
}
public void paint(Graphics g) { ... } // from Canvas
...
}
60 Packages
Example 73 The following example shows an application of the antriores capitulos includes the application of threads, to cronometrar, and connection of data base, taking as example a distributing company of equipment of I compute.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
public class Bienvenida extends Frame{ public int PosicionSearch=1; private Panel MiPanelPrincipal; private JFrame FormPrincipal; private TextArea AreaDeListadoBegin; static String[ ] BotonDialogoBegin = { “Aceptar”, “Cancelar” }; JScrollPane AgregarTabla;/// JPanel DatosPanel; JLabel lblUsuario; JTextField Usuario; JLabel lblContraseña; JTextField Contraseña;

public Bienvenida(){ MiPanelPrincipal=new Panel (new GridLayout (2,1)); Panel PanelCtrl=new Panel (new FlowLayout(FlowLayout.CENTER)); AreaDeListadoBegin=new TextArea(); AreaDeListadoBegin.setEnabled(false);

Button BotonDesbloquear=new Button(“Aceptar”);

Button BotonCancelar=new Button(“Cancelar”);

lblUsuario = new JLabel(” Nombre de Usuario: “, JLabel.LEFT); lblContraseña = new JLabel(“Contraseña: “, JLabel.LEFT); Usuario=new JTextField(15); Contraseña=new JTextField(15); JPanel EtiquetaPanel = new JPanel(false); EtiquetaPanel.setLayout(new GridLayout(2, 2)); DatosPanel = new JPanel(false); DatosPanel.setLayout(new BoxLayout(DatosPanel,BoxLayout.X_AXIS)); EtiquetaPanel.add(lblUsuario); EtiquetaPanel.add(Usuario); EtiquetaPanel.add(lblContraseña); EtiquetaPanel.add(Contraseña); DatosPanel.add(EtiquetaPanel);

AreaDeListadoBegin.setText(”“) ; AreaDeListadoBegin.append(” “); AreaDeListadoBegin.append(” “); AreaDeListadoBegin.append(” “); AreaDeListadoBegin.append(” “);

AreaDeListadoBegin.append(” “);

MiPanelPrincipal.add(AreaDeListadoBegin); MiPanelPrincipal.add(PanelCtrl);

PanelCtrl.add(BotonDesbloquear); PanelCtrl.add(BotonCancelar);

BotonCancelar.addActionListener(new Cancelar());

FormPrincipal = new JFrame(“PAPELERIA JELLO ‘’ A D S I J E L ‘’”); FormPrincipal.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);}}); FormPrincipal.setBackground(Color.lightGray); FormPrincipal.getContentPane().add(MiPanelPrincipal); Desbloquear(); }

public void Desbloquear() { if(JOptionPane.showOptionDialog(AgregarTabla, DatosPanel, “Datos de Usuario”, JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, BotonDialogoBegin, BotonDialogoBegin0)==0){ Thread s, concurrent execution, and synchronization 69

Conexion InstanciaConsulta=new Conexion (Usuario.getText(),Contraseña.getText()); PosicionSearch=InstanciaConsulta.PosicionEncontrada();

if(PosicionSearch!=0){ FormPrincipal.pack(); FormPrincipal.setVisible(true); FormPrincipal.setBounds(200, 200, 450, 240); } else{ JOptionPane.showMessageDialog(null ,“Usuario o Contraseña incorrecta”, “Error”,2); Desbloquear(); } } else System.exit(0);
}

private class Cancelar implements ActionListener{ public void actionPerformed(ActionEvent Evento){ System.exit(0); } } public static void main (String [] args){ new Bienvenida(); }
}

import java.sql.*;
public class Conexion{ private int Posicion=0; Conexion(String RecibeUsuario,String RecibeContraseña){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM Contraseña”); Personas.moveToInsertRow(); while(Personas.next()){ String compUsuario=Personas.getString(“Usuario”); String compContraseña=Personas.getString(“Contraseña”);

if(compUsuario.equalsIgnoreCase(RecibeUsuario) && compContraseña.equalsIgnoreCase(RecibeContraseña)){ Posicion=Personas.getRow(); break; } }

Personas.close(); Conexion.close(); SentenciaSQL.close();

} catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e);

} } public int PosicionEncontrada(){ return Posicion;
}
}

import java.sql.*;

public class ObBorrado{

ObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close();

} catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }

import java.sql.*;

public class ObBorrado{

ObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;
public class ObConsulta{ private int Posicion=0; private ObRegistro DatosPersona; ObConsulta(String DNIPedido){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”); Personas.moveToInsertRow(); while(Personas.next()){ String Num=Personas.getString(“Num_Cli”);

if(Num.equalsIgnoreCase(DNIPedido)){ Posicion=Personas.getRow(); String Nombre=Personas.getString(“Nom_Cli”); String RFC=Personas.getString(“RFC_Cli”); String DIR=Personas.getString(“Dir_Cli”);

String TEL=Personas.getString(“Tel_Cli”); String Ciudad=Personas.getString(“Cd_Cli”); String CP=Personas.getString(“CP_Cli”);

DatosPersona=new ObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

break;

} }

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

}

catch(SQLException e){ System.out.println(e); } } public int PosicionEncontrada(){ return Posicion;

}
public ObRegistro DameDatos(){ return DatosPersona; }
}

import java.sql.*;

public class ObInsercion{

ObInsercion(ObRegistro Datos){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.moveToInsertRow(); Personas.updateString(“Num_Cli”,Datos.DameNum()); Personas.updateString(“Nom_Cli”,Datos.DameNombre());

Personas.updateString(“RFC_Cli”,Datos.DameRFC()); Personas.updateString(“Dir_Cli”,Datos.DameDIR()); Personas.updateString(“Tel_Cli”,Datos.DameTEL()); Personas.updateString(“Cd_Cli”,Datos.DameCiudad()); Personas.updateString(“CP_Cli”,Datos.DameCP()); Personas.insertRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }

import java.sql.*;

public class ObModificacion{

ObModificacion(int PosicionBuscada, ObRegistro Datos){

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”); Personas.absolute(PosicionBuscada); Personas.updateString(“Num_Cli”,Datos.DameNum()); Personas.updateString(“Nom_cli”,Datos.DameNombre()); Personas.updateString(“RFC_Cli”,Datos.DameRFC()); Personas.updateString(“Dir_Cli”,Datos.DameDIR()); Personas.updateString(“Tel_Cli”,Datos.DameTEL()); Personas.updateString(“Cd_Cli”,Datos.DameCiudad()); Personas.updateString(“CP_Cli”,Datos.DameCP()); Personas.updateRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;

public class ObPosicionamiento{

private ObRegistro DatosPersona; private int Posicion;

ObPosicionamiento(String Accion, int Posicion){ int IDAccion, Edad; String Num,Nombre,RFC,DIR,TEL,Ciudad,CP; boolean PosicionCorrecta=false;

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM CLIENTES”);

Personas.absolute(Posicion);

IDAccion=Integer.parseInt(Accion); switch(IDAccion){ case 0: PosicionCorrecta=Personas.last(); break; case 1: PosicionCorrecta=Personas.first(); break; case 2: PosicionCorrecta=Personas.relative(-5); break; case 3: PosicionCorrecta=Personas.previous(); break; case 4: PosicionCorrecta=Personas.next(); break; case 5: PosicionCorrecta=Personas.relative(+5); break; }

if(PosicionCorrecta){

this.Posicion=Personas.getRow(); Num=Personas.getString(“Num_Cli”); Nombre=Personas.getString(“Nom_Cli”); RFC=Personas.getString(“RFC_Cli”); DIR=Personas.getString(“Dir_Cli”); TEL=Personas.getString(“Tel_Cli”); Ciudad=Personas.getString(“Cd_Cli”); CP=Personas.getString(“CP_Cli”); } else{ this.Posicion=Posicion;

Num=”——-”; Nombre=”——-”; RFC=”——-”; DIR=”——-”; TEL=”——-”; Ciudad=”——-”; CP=”——-”; } DatosPersona=new ObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e); } }

public int Posicion(){ return Posicion; }

public ObRegistro DameDatos(){ return DatosPersona; }

}

public class ObRegistro {
private String Num,Nombre,RFC,DIR,TEL,Ciudad,CP;

Thread s, concurrent execution, and synchronization 81

ObRegistro (String Num, String Nombre, String RFC, String DIR, String TEL, String Ciudad, String CP){

this.Num=Num;
this.Nombre=Nombre;

this.RFC=RFC;
this.DIR=DIR;
this.TEL=TEL;
this.Ciudad=Ciudad;
this.CP=CP;

}
String DameNum(){
return Num;
}
String DameNombre(){
return Nombre;
}
String DameRFC(){
return RFC;
}
String DameDIR(){
return DIR;
}
String DameTEL(){
return TEL;
}
String DameCiudad(){
return Ciudad;
}
String DameCP(){
return CP;

}
}

import java.sql.*;

public class PObBorrado{

PObBorrado(int PosicionBuscada){
try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos = “jdbc:odbc:ADSIJEL”; Connection Conexion=DriverManager.getConnection (BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas=SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”);

Personas.absolute(PosicionBuscada); Personas.deleteRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){

System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); }

} }

import java.sql.*;
public class PObConsulta{ private int Posicion=0; private PObRegistro DatosPersona; PObConsulta(String DNIPedido){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”); Personas.moveToInsertRow(); while(Personas.next()){ String Num=Personas.getString(“Num_Prov”); if(Num.equalsIgnoreCase(DNIPedido)){ Posicion=Personas.getRow(); String Nombre=Personas.getString(“Nom_Prov”); String RFC=Personas.getString(“RFC_Prov”); String DIR=Personas.getString(“Dir_Prov”); String TEL=Personas.getString(“Tel_Prov”); String Ciudad=Personas.getString(“Cd_Prov”); String CP=Personas.getString(“CP_Prov”);

DatosPersona=new PObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

break;

} }

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e);

} } public int PosicionEncontrada(){ return Posicion;

}
public PObRegistro DameDatos(){ return DatosPersona; }
}
import java.sql.*;

public class PObInsercion{

PObInsercion(PObRegistro PDatos){ try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”);

Personas.moveToInsertRow(); Personas.updateString(“Num_Prov”,PDatos.DameNum()); Personas.updateString(“Nom_Prov”,PDatos.DameNombre()); Personas.updateString(“RFC_Prov”,PDatos.DameRFC()); Personas.updateString(“Dir_Prov”,PDatos.DameDIR()); Personas.updateString(“Tel_Prov”,PDatos.DameTEL()); Personas.updateString(“Cd_Prov”,PDatos.DameCiudad()); Personas.updateString(“CP_Prov”,PDatos.DameCP()); Personas.insertRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } } }

import java.sql.*;

public class PObModificacion{

PObModificacion(int PosicionBuscada, PObRegistro PDatos){

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”; Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”); Personas.absolute(PosicionBuscada); Personas.updateString(“Num_Prov”,PDatos.DameNum()); Personas.updateString(“Nom_Prov”,PDatos.DameNombre()); Personas.updateString(“RFC_Prov”,PDatos.DameRFC()); Personas.updateString(“Dir_Prov”,PDatos.DameDIR()); Personas.updateString(“Tel_Prov”,PDatos.DameTEL()); Personas.updateString(“Cd_Prov”,PDatos.DameCiudad()); Personas.updateString(“CP_Prov”,PDatos.DameCP()); Personas.updateRow();

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”); } catch(SQLException e){ System.out.println(e); } }
}

import java.sql.*;

public class PObPosicionamiento{

private PObRegistro DatosPersona; private int Posicion;

PObPosicionamiento(String Accion, int Posicion){ int IDAccion, Edad; String Num,Nombre,RFC,DIR,TEL,Ciudad,CP; boolean PosicionCorrecta=false;

try{ Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String BaseDeDatos=“jdbc:odbc:ADSIJEL”;

Connection Conexion = DriverManager.getConnection(BaseDeDatos); Statement SentenciaSQL=Conexion.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet Personas =SentenciaSQL.executeQuery(“SELECT * FROM PROVEEDOR”);

Personas.absolute(Posicion);

IDAccion=Integer.parseInt(Accion); switch(IDAccion){ case 0: PosicionCorrecta=Personas.last(); break; case 1: PosicionCorrecta=Personas.first(); break; case 2: PosicionCorrecta=Personas.relative(-5); break; case 3: PosicionCorrecta=Personas.previous(); break; case 4: PosicionCorrecta=Personas.next(); break; case 5: PosicionCorrecta=Personas.relative(+5); break; } if(PosicionCorrecta){ this.Posicion=Personas.getRow(); Num=Personas.getString(“Num_Prov”); Nombre=Personas.getString(“Nom_Prov”); RFC=Personas.getString(“RFC_Prov”); DIR=Personas.getString(“Dir_Prov”); TEL=Personas.getString(“Tel_Prov”); Ciudad=Personas.getString(“Cd_Prov”); CP=Personas.getString(“CP_Prov”); } else{ this.Posicion=Posicion;

Num=”——-”; Nombre=”——-”; RFC=”——-”; DIR=”——-”; TEL=”——-”; Ciudad=”——-”; CP=”——-”; } DatosPersona=new PObRegistro(Num,Nombre,RFC,DIR,TEL,Ciudad,CP);

Personas.close(); Conexion.close(); SentenciaSQL.close(); } catch(ClassNotFoundException e){ System.out.println(“Clase no encontrada”);

} catch(SQLException e){ System.out.println(e); } }

public int Posicion(){ return Posicion; }

public PObRegistro DameDatos(){ return DatosPersona; }

}

public class PObRegistro {
private String Num,Nombre,RFC,DIR,TEL,Ciudad,CP;
PObRegistro (String Num, String Nombre, String RFC, String DIR, String TEL, String Ciudad, String CP){

this.Num=Num;
this.Nombre=Nombre;
this.RFC=RFC;
this.DIR=DIR;
this.TEL=TEL;
this.Ciudad=Ciudad;
this.CP=CP;

}
String DameNum(){

return Num;
}
String DameNombre(){
return Nombre;
}
String DameRFC(){
return RFC;
}
String DameDIR(){
return DIR;
}
String DameTEL(){
return TEL;
}
String DameCiudad(){
return Ciudad;
}
String DameCP(){
return CP;
}

}

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
import java.text.*; public class Principal extends Applet implements Runnable{

public int PosicionSearch=1; private boolean band=false; private Panel MiPanelPrincipal; private JFrame FormPrincipal; private TextArea AreaDeListadoBegin; static String[] BotonDialogoBegin = { “Aceptar”, “Cancelar” }; JPanel DatosPanel; JLabel lblUsuario; JTextField Usuario; JLabel lblContraseña; JTextField Contraseña;

private volatile Thread timer; // The thread that displays clock private volatile Thread Cronometro; private SimpleDateFormat formatter; // Formats the date displayed private String lastdate,lastdate2,lastdate3; // String to hold date displayed private Date currentDate; // Used to get date to display TextField txt1=new TextField(6); private TextField CampoNum_Cli; private TextField CampoNom_Cli; private TextField CampoRFC_Cli; private TextField CampoDir_Cli; private TextField CampoTel_Cli; private TextField CampoCd_Cli; private TextField CampoCP_Cli;

private TextField CampoNum_Prov; private TextField CampoNom_Prov; private TextField CampoRFC_Prov; private TextField CampoDir_Prov; private TextField CampoTel_Prov;

private TextField CampoCd_Prov; private TextField CampoCP_Prov;

private TextField CampoNum_Prod; private TextField CampoNom_Prod; private TextField CampoDescripcion; private TextField CampoUnidad; private TextField CampoFecha_ingreso; private TextField CampoCan_min; private TextField CampoCan_max; private TextField CampoExistencia; private TextField CampoPrecio_Prod; private TextField CampoPrecio_Vta;

private TextField NumeroProducto; private TextField NombreProducto; private TextField Descrip; private TextField Precio; private TextField Cant; private TextField Subtotal; private TextField Total;

JScrollPane AgregarTabla; static String[] BotonDialogo = { “ Si “,” No “ };

public int PosicionBuscada=1; public int PPosicionBuscada=1; public int PRPosicionBuscada=1;

private JScrollPane PanelTabla;

private JScrollPane PPanelTabla; private JScrollPane PRPanelTabla; private JScrollPane PanelTablaVarios; private JScrollPane PanelVentas;

private TipoTabla VariosTabla; private TipoTabla Tabla; private TipoTabla PTabla; private TipoTabla PRTabla;

private ListarJDBC BaseDeDato; private JFrame Formulario,Formulario2,Formulario3,Formulario4,Formulario5,Formulario6; private JPanel MiPanel,MiPanel2,MiPanel3,MiPanel4,MiPanel5; private JLabel etiqReloj,preg;

public Principal(){

MiPanelPrincipal=new Panel (new GridLayout (2,1)); Panel PanelCtrl=new Panel (new FlowLayout(FlowLayout.CENTER)); AreaDeListadoBegin=new TextArea(); AreaDeListadoBegin.setEnabled(false);

Button BotonDesbloquear=new Button(“Aceptar”);

Button BotonCancelar=new Button(“Cancelar”);

lblUsuario = new JLabel(” Nombre de Usuario: “, JLabel.LEFT); lblContraseña = new JLabel(“Contraseña: “, JLabel.LEFT); Usuario=new JTextField(15); Contraseña=new JTextField(15); JPanel EtiquetaPanel = new JPanel(false); EtiquetaPanel.setLayout(new GridLayout(2, 2)); DatosPanel = new JPanel(false); DatosPanel.setLayout(new BoxLayout(DatosPanel,BoxLayout.X_AXIS)); EtiquetaPanel.add(lblUsuario); EtiquetaPanel.add(Usuario); EtiquetaPanel.add(lblContraseña); EtiquetaPanel.add(Contraseña); DatosPanel.add(EtiquetaPanel);

AreaDeListadoBegin.setText(”“) ; AreaDeListadoBegin.append(“Autorizado a:ntt María Elena Fernández Márqueznn”); AreaDeListadoBegin.append(“tANÁLISIS Y DISEÑO DEL SISTEMA DE INFORMACION PARA LAn”);

AreaDeListadoBegin.append(“tttPAPELERIA JELANSA:nn”); AreaDeListadoBegin.append(“t’‘ A D S I J E L ‘’”); AreaDeListadoBegin.append(“nnntttB I E N V E N I D O”); MiPanelPrincipal.add(AreaDeListadoBegin); MiPanelPrincipal.add(PanelCtrl);

PanelCtrl.add(BotonDesbloquear); PanelCtrl.add(BotonCancelar);

BotonCancelar.addActionListener(new Cancelar());

etiqReloj=new JLabel(“Hora Actual:”); preg=new JLabel(“¿Realmente desea salir del Sistema ADSIJEL?”); MiPanel=new JPanel (new GridLayout (1,2)); MiPanel2=new JPanel (new GridLayout (1,1)); MiPanel3=new JPanel (new GridLayout (1,1)); MiPanel4=new JPanel (new GridLayout (1,1)); MiPanel5=new JPanel (new GridLayout (1,1));

Panel Panel1=new Panel (new GridLayout (1,1)); Panel Panel2=new Panel (new GridLayout (1,1)); Panel Panel3=new Panel (new GridLayout (1,1)); Panel Panel4=new Panel (new GridLayout (1,1));


Panel Panel5=new Panel (new GridLayout (1,1));

Panel PanelHora=new Panel (new GridLayout (6,1));

Panel PanelReloj=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PanelReloj2=new Panel (new FlowLayout(FlowLayout.CENTER));

Button SalirSistema=new Button(“Cerrar Sistema”); Button BotonProducto=new Button(“PRODUCTOS”); Button BotonVenta=new Button(“VENTAS”); Button BotonProveedor=new Button(“PROVEEDOR”); Button BotonCliente=new Button(“CLIENTES”); Button BotonVarios=new Button(“CLIENTES/PROVEEDORES”);

Panel1.add(BotonProducto); Panel2.add(BotonVenta); Panel3.add(BotonProveedor); Panel4.add(BotonCliente); Panel5.add(BotonVarios);

BotonCliente.addActionListener(new Cliente()); BotonProveedor.addActionListener(new Proveedor()); BotonProducto.addActionListener(new Producto());

Panel PanelIzq=new Panel (new GridLayout (9,1));

Panel PanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelRFC=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelDIR=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelTEL=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelCiudad=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PanelCP=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PPanelIzq=new Panel (new GridLayout (9,1)); Panel PPanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelRFC=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelDIR=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelTEL=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelCiudad=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PPanelCP=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PRPanelIzq=new Panel (new GridLayout (12,1)); Panel PRPanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PRPanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelDes=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelUnidad=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelFing=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelCmin=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelCmax=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelExistencia=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelPprod=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel PRPanelPvta=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel VtaPanelIzq=new Panel (new GridLayout (12,1)); Panel VtaPanelDNI=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelNombre=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelDes=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelPrecio=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelCant=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelSub=new Panel (new FlowLayout(FlowLayout.LEFT)); Panel VtaPanelTotal=new Panel (new FlowLayout(FlowLayout.LEFT));

Panel PanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Panel PPanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PPanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Panel PRPanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel PRPanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Panel VtaPanelAccion=new Panel (new FlowLayout(FlowLayout.CENTER)); Panel VtaPanelControles=new Panel (new FlowLayout(FlowLayout.CENTER));

Label EtiquetaNum=new Label (“Numero”); Label EtiquetaNombre=new Label (“Nombre”); Label EtiquetaRFC=new Label (“RFC”); Label EtiquetaDIR=new Label (“Dirección”); Label EtiquetaTEL=new Label (“Telefono”); Label EtiquetaCiudad=new Label (“Ciudad”); Label EtiquetaCP=new Label (“Cod. Postal”);

Label EtiquetaPNum=new Label (“Numero”); Label EtiquetaPNombre=new Label (“Nombre”); Label EtiquetaPRFC=new Label (“RFC”); Label EtiquetaPDIR=new Label (“Dirección”); Label EtiquetaPTEL=new Label (“Telefono”); Label EtiquetaPCiudad=new Label (“Ciudad”); Label EtiquetaPCP=new Label (“Cod. Postal”);

Label EtiquetaNum_Prod=new Label (“Numero”); Label EtiquetaNom_Prod=new Label (“Nombre”); Label EtiquetaDescripcion=new Label (“Descripción”); Label EtiquetaUnidad=new Label (“Unidad”); Label EtiquetaFecha_ingreso=new Label (“Fecha Ingreso”); Label EtiquetaCan_min=new Label (“Cantidad Minima”); Label EtiquetaCan_max=new Label (“Cantidad Maxima”); Label EtiquetaExistencia=new Label (“Existencia”); Label EtiquetaPrecio_Prod=new Label (“Precio Producto”); Label EtiquetaPrecio_Vta=new Label (“Precio Venta”);

Label EtiquetaNum_ProdVta=new Label (“Numero”); Label EtiquetaNom_ProdVta=new Label (“Nombre”); Label EtiquetaDescripcionVta=new Label (“Descripción”); Label EtiquetaPrecio=new Label (“Precio”); Label EtiquetaCant=new Label (“Cantidad”); Label EtiquetaSub=new Label (“Subtotal”); Label EtiquetaTotal=new Label (“Total”);

CampoNum_Cli=new TextField (10); CampoNom_Cli=new TextField (30); CampoRFC_Cli=new TextField (15); CampoDir_Cli=new TextField (40); CampoTel_Cli=new TextField (12); CampoCd_Cli=new TextField (20); CampoCP_Cli=new TextField (10);

CampoNum_Prov=new TextField (10); CampoNom_Prov=new TextField (30); CampoRFC_Prov=new TextField (15); CampoDir_Prov=new TextField (40); CampoTel_Prov=new TextField (12); CampoCd_Prov=new TextField (20); CampoCP_Prov=new TextField (10);

CampoNum_Prod=new TextField (10); CampoNom_Prod=new TextField (30); CampoDescripcion=new TextField (30); CampoUnidad=new TextField (10); CampoFecha_ingreso=new TextField (10); CampoCan_min=new TextField (6); CampoCan_max=new TextField (6); CampoExistencia=new TextField (6); CampoPrecio_Prod=new TextField (6); CampoPrecio_Vta=new TextField (6);

NumeroProducto=new TextField (10); NombreProducto=new TextField (40); Descrip=new TextField (40); Precio=new TextField (10); Cant=new TextField (10); Subtotal=new TextField (12); Total=new TextField (12);

Button BotonConsultar=new Button(“Buscar”); Button BotonModificar=new Button(“Modificar”); Button BotonInsertar=new Button(“Insertar”);

Button BotonBorrar=new Button(“Borrar”); Button BotonListar=new Button(“Reporte”);

Button BotonPrimero=new Button(”|=”); BotonPrimero.setName(“1”); Button BotonMenosCinco=new Button(”—”); BotonMenosCinco.setName(“2”); Button BotonAnterior=new Button(”-”); BotonAnterior.setName(“3”); Button BotonSiguiente=new Button(”+”); BotonSiguiente.setName(“4”); Button BotonMasCinco=new Button(”++”); BotonMasCinco.setName(“5”); Button BotonUltimo=new Button(”>|”); BotonUltimo.setName(“0”);

Button BotonPConsultar=new Button(“Buscar”); Button BotonPModificar=new Button(“Modificar”); Button BotonPInsertar=new Button(“Insertar”); Button BotonPBorrar=new Button(“Borrar”); Button BotonPListar=new Button(“Reporte”);

Button BotonPPrimero=new Button(”|=”); BotonPPrimero.setName(“1”); Button BotonPMenosCinco=new Button(”—”); BotonPMenosCinco.setName(“2”); Button BotonPAnterior=new Button(”-”); BotonPAnterior.setName(“3”); Button BotonPSiguiente=new Button(”+”); BotonPSiguiente.setName(“4”); Button BotonPMasCinco=new Button(”++”); BotonPMasCinco.setName(“5”); Button BotonPUltimo=new Button(”>|”); BotonPUltimo.setName(“0”);

Button BotonPRConsultar=new Button(“Buscar”); Button BotonPRModificar=new Button(“Modificar”); Button BotonPRInsertar=new Button(“Insertar”); Button BotonPRBorrar=new Button(“Borrar”); Button BotonPRListar=new Button(“Reporte”);

Button BotonPRPrimero=new Button(”|=”); BotonPRPrimero.setName(“1”); Button BotonPRMenosCinco=new Button(”—”); BotonPRMenosCinco.setName(“2”); Button BotonPRAnterior=new Button(”-”); BotonPRAnterior.setName(“3”); Button BotonPRSiguiente=new Button(”+”); BotonPRSiguiente.setName(“4”); Button BotonPRMasCinco=new Button(”++”); BotonPRMasCinco.setName(“5”); Button BotonPRUltimo=new Button(”>|”); BotonPRUltimo.setName(“0”);

Button BotonBuscar=new Button(“Buscar”); Button BotonAgregar=new Button(“Agregar”);

PanelTabla = crearTabla(); PanelTabla.setBorder(new BevelBorder(BevelBorder.LOWERED)); PPanelTabla = PcrearTabla(); PPanelTabla.setBorder(new BevelBorder(BevelBorder.LOWERED));

PRPanelTabla = PRcrearTabla(); PRPanelTabla.setBorder(new BevelBorder(BevelBorder.LOWERED));

PanelTablaVarios= PRcrearTabla(); PanelTablaVarios.setBorder(new BevelBorder(BevelBorder.LOWERED));

PanelVentas= PRcrearTabla(); PanelVentas.setBorder(new BevelBorder(BevelBorder.LO



[ Enlace | Sin comentarios :'( ] del.icio.us del.icio.us Estrella este post ***** General
comparte esto
Comparte esta entrada (del.icio.us, por correo, etc) o agrega este blog a tu Google Reader.

Entradas relacionadas:
  1. Manual Java
  2. MAnual de Programaciòn en Java.
  3. Protocolo SNAP, el mas rapido hasta hoy.
  4. Manual Java 3ra. parte
  5. En lo Profundo de la Soledad.
Si usted tiene una cuenta en ymipollo.com, identifíquese:
Usuario: Password: (recordar identificación en este blog)
Escriba su comentario:
Por favor escriba respecto al post, procure revisar su ortografía. Si su comentario no es respecto al tema, por favor no lo haga.

Usted escribirá este mensaje como:
Es posible que su comentario no aparezca de forma inmediata (o que nunca aparezca) eso depende de la decisión del autor de este blog.

enviarme correo cuando alguien comente suscribirse a este post.

RSS
Blog | Comentarios