Vous êtes sur la page 1sur 12

public class ComponentEvent extends AWTEvent A low-level event which indicates that a component moved, changed size, or changed

visibility (also, the root class for the other component-level events). Component events are provided for notification purposes ONLY; The AWT will automatically handle component moves and resizes internally so that GUI layout works properly regardless of whether a program is receiving these events or not. In addition to serving as the base class for other component-related events (InputEvent, FocusEvent, WindowEvent, ContainerEvent), this class defines the events that indicate changes in a component's size, position, or visibility. This low-level event is generated by a component object (such as a List) when the component is moved, resized, rendered invisible, or made visible again. The event is passed to every ComponentListener or ComponentAdapter object which registered to receive such events using the component's addComponentListener method. (ComponentAdapter objects implement the ComponentListener interface.) Each such listener object gets this ComponentEvent when the event occurs.

15
The FlowLayout layout manager arranges components in a directional flow, much like lines of text in a paragraph. It arranges components horizontally until no more components fit on the same line, then it places them on another line.
java.awt

Class FlowLayout

java.lang.Object
o

java.awt.FlowLayout

All Implemented Interfaces: LayoutManager, Serializable

public class FlowLayout extends Object implements LayoutManager, Serializable

A flow layout arranges components in a directional flow, much like lines of text in a paragraph. The flow direction is determined by the container's componentOrientation property and may be one of two values:
o o ComponentOrientation.LEFT_TO_RIGHT ComponentOrientation.RIGHT_TO_LEFT

Flow layouts are typically used to arrange buttons in a panel. It arranges buttons horizontally until no more buttons fit on the same line. The line alignment is determined by the align property. The possible values are:
o o o o o LEFT RIGHT CENTER LEADING TRAILING

Constructor and Description FlowLayout()


Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap. FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. FlowLayout(int align, int hgap, int vgap) Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.
javax.swing.JFrame; javax.swing.JButton; java.awt.FlowLayout; java.awt.Container;

import import import import

public class LayoutExample extends JFrame { public LayoutExample() { this.setTitle("FlowLayoutDemo"); // get the top-level container in the Frame (= Window) Container contentPane = this.getContentPane(); // set the layout of this container contentPane.setLayout(new FlowLayout()); // add buttons in this container this.add((new JButton("Button 1"))); this.add((new JButton("Button 2"))); this.add((new JButton("Button 3"))); this.add((new JButton("Long-Named Button 4"))); this.add((new JButton("5"))); // exit the application when clicking on the right close-button this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public static void main(String[] args) { LayoutExample example = new LayoutExample();

example.setVisible(true); } }

This code shows 5 buttons alongside each other on the same line:

16 javaBeans technology is the component architecture for the Java 2 Platform, Standard Edition (J2SE). JavaBeans components (beans) are reusable software programs that you can develop and assemble easily to create sophisticated applications. JavaBeans technology is based on the JavaBeans specification. JavaBeans components, or beans, are reusable software components that follow simple naming and design conventions so they present a standard interface to other beans, programs, and tools. The installation of the JavaBeans Development Kit involves the following. The JavaBeans Development Kit (BDK) downloads into a single file. You will need to execute the kit (in Windows) or unpack (in Unix) this file in order to install the complete BDK. Unlike the Java Development Kit (JDK), none of the BDK components are optional, so the installation is very simple. The BDK contains both information and tools to aid you as you design and develop JavaBeans components. Select a part of the BDK to learn more about it: 1. 2. 3. 4. The BeanBox test container Example Beans and source code API source code JavaBeans tutorial

The BeanBox test container To run the BeanBox, execute the run.bat file, which is located in the beanbox directory beneath the main Bdk directory.The run.bat file makes use of the Java interpreter provided with the JDK. The Java interpreter is located in the JDK bin directory beneath the main jdk directory. This directory must be included in your system path in order for the run.bat file to function properly. The BeanBox user interface When the BeanBox is running, it displays three different windows: 1. ToolBox window 2. BeanBox window 3. Properties window

OUTPUT

10q
A character-oriented input stream is called a reader. A character-oriented output stream is called a writer. The Reader and Writer hierarchies mirror the byte-oriented input and output stream hierarchies, respectively. For example, here is the Reader hierarchy:

Of course Readers provide character-oriented versions of the InputStream operations: read, mark, reset, etc. while Writers provide character-oriented versions of the OutputStream operations: write, close, flush, etc. For example, here is a simple block of code that creates a reader with a string as its source, then prints the characters in the string one at a time:

StringReader reader = new StringReader("testing: one, two, three"); while(true) { try { int next = reader.read(); if (next == -1) break; System.out.println("next = " + (char)next); } catch(IOException e) { System.err.println(e.getMessage()); break; } } // while

Byte to Character Conversion


Sources for readers and destinations for writers can be strings, pipes, filters, and of course, byteoriented input and output streams. The InputStreamReader class serves as a bridge between byte-

oriented input streams and readers, while the OutputStreamReader is the bridge connecting writers to byte-oriented output streams. The interesting feature is that when constructing a reader, the user may specify a character set to be used in translating between the bytes coming from the source and the character codes being read. Similarly, when constructing a writer, the user may specify a character set to be used to translate the character codes being written with the bytes being sent to the destination. For example:

OutputStream stream = ...; OutputStreamWriter writer = new OutputStreamWriter(stream, "US_ASCII");


See the Javadoc page for the Charset class for more details. If the character set isn't specified, the default character set for the host machine is used. This means the same Java program can run on any computer in the world, regardless of the underlying character set. To demonstrate this, the following program creates a file using a writer:

PrintWriter pw = null;; try { pw = new PrintWriter(new BufferedWriter(new FileWriter("text"))); pw.write("is were am be are being was been\n"); pw.write("A squid eating dough is fast and bulbous\n"); pw.write("These are the voyages of the star ship Enterprise\n"); pw.close(); } catch(IOException e) { System.err.println(e.getMessage()); pw.close(); }
Files created by writers can be read by local text editors:

Java can also read from text files created by local text editors:

BufferedReader br = null; try { br = new BufferedReader(new FileReader("text")); while(true) { String next = br.readLine(); if (next == null) break; System.out.println("next = " + next); } } catch(IOException e) { System.err.println(e.getMessage()); try { br.close(); } catch(IOException e1) { System.err.println(e1.getMessage()); } }

Consoles
The Java system class provides the only streams for communicating with the console window and the keyboard:

class System { public static PrintStream out, err; // console window public static InputStream in; // keyboard // etc. }
System.in only provides the ability to read one byte at a time from the keyboard, and of course print streams are not sensitive to the underlying character set of the host machine. To remedy this defect I have a reusable Console class (see jutil.Console):

public class Console { protected BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); protected PrintWriter stdout = new PrintWriter( new BufferedWriter( new OutputStreamWriter(System.out)), true); protected PrintWriter stderr = new PrintWriter( new BufferedWriter( new OutputStreamWriter(System.err)), true);
A control loop perpetually prompts the user for a command, reads the command, then executes it:

public void controlLoop() { while(true) {

try { stdout.print("-> "); stdout.flush(); // force the write String cmmd = stdin.readLine(); if (cmmd == null) { stdout.println("type \"help\" for commands"); continue; } cmmd = cmmd.trim(); // trim white space if (cmmd.equalsIgnoreCase("quit")) break; if (cmmd.equalsIgnoreCase("help")) { stdout.println("Sorry, no help is available"); continue; } if (cmmd.equalsIgnoreCase("about")) { stdout.println("All rights reserved"); continue; } stdout.println(execute(cmmd)); } catch(Exception e) { stderr.println(e.getMessage()); } } // while stdout.println("bye"); } // controlLoop
Executing a command must be defined in an extension:

// override in a subclass: protected String execute(String cmmd) throws Exception { if (cmmd.equalsIgnoreCase("throw")) { throw new Exception("exception intentionally thrown"); } return "echo: " + cmmd; }
Here's a simple test harness:

public static void main(String[] args) { Console ui = new Console(); ui.controlLoop(); } } // Console
Program output:

-> help Sorry, no help is available -> about

All rights reserved -> hello echo: hello -> throw exception intentionally thrown -> quit bye 12q Consider the classic queuing problem, where one thread is producing some data and another is consuming it. To make the problem more interesting, suppose that the producer has to wait until the consumer is finished before it generates more data. In a polling system, the consumer would waste many CPU cycles while it waited for the producer to produce. Once the producer was finished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so on. Clearly, this situation is undesirable. To avoid polling, Java includes an elegant interprocess communication mechanism via the following methods:

wait( ): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ): This method wakes up the first thread that called wait( ) on the same object. notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.c The highest priority thread will run first.

These methods are implemented as final methods in Object, so all classes have them. All three methods can be called only from within a synchronized context. These methods are declared within Object. Various forms of wait( ) exist that allow you to specify a period of time to wait.

Example:
The following sample program consists of four classes: Q, the queue that you're trying to synchronize; Producer, the threaded object that is producing queue entries; Consumer, the threaded object that is consuming queue entries; and PC, the tiny class that creates the single Q, Producer, and Consumer. The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions, as shown here:
class Q { int n; boolean valueSet = false; synchronized int get() { if(!valueSet) try {

wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while(true) { q.get(); } } } class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } }

Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue. When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells the Consumer that it should now remove it. Here is some output from this program, which shows the clean synchronous behavior:
Put: Got: Put: Got: Put: Got: Put: Got: Put: Got: 1 1 2 2 3 3 4 4 5 5

import java.util.Arrays; public class ArrayStringSorting1 { public static void main(String[] args) { String[] arrayList = new String[] { "Delhi", "Chennai", "Bangalore", "Bombay", "New York" }; String temp=""; System.out.println("Before sorting the Array: " + Arrays.asList(arrayList)); // Logic for sorting for (int i=0;i<=arrayList.length-1;i++) { for (int j=i+1;j<arraylist.length;j++) { if (arrayList[i].compareTo(arrayList[j])>0 ) { temp=arrayList[i]; arrayList[i]=arrayList[j]; arrayList[j]=temp; } } } System.out.println("After sorting the Array: "); for (int i=0;i<arrayList.length;i++)

// Inerchange of element

{ System.out.print(arrayList[i] +" "); } } } </arraylist.length;j++)

Running the Program java ArrayStringSorting1 Output : Before sorting the Array: [Delhi, Chennai, Bangalore, Bombay, New York] After sorting the Array: Bangalore Bombay Chennai Delhi New York

Vous aimerez peut-être aussi