You are on page 1of 46
Components A component is the fundamental user interface object in Java. Everything you see on the display in a Java application is a component. This includes things like windows, panels, buttons, checkboxes, scrollbars, lists, menus, and text fields. To be used, a component usually must be placed in a container. Container objects group components, ar- range them for display using a layout manager, and associate them with a particular display device. All Swing components are derived from the abstract javax.swing.JComponent class, as you saw in Figure 16-1. For example, the JButton class is a subclass of AbstractButton, which is itself a subclass of the JComponent class. JComponent is the root of the Swing component hierarchy, but it descends from the AWT Con- tainer class. At this bottom level, Swing is based on AWT, so our conversation occasionally delves into the AWT package. Container's superclass is Component, the root of all AWT components, and Component's superclass is, finally, Object. Be- cause JComponent inherits from Container, it has the capabilities of both a component and a container. AWT and Swing, then, have paral- lel hierarchies. The root of AWT's hierarchy is Component, while Swing's components are based on JComponent. You'll find similar classes in both hierarchies, such as Button and JButton, List, and JList. But Swing is much Enabling and Disabling Components Standard Swing components can be turned on and off by calling the setEnabled( ) method. When a component such as a JButton or JTextField is disabled, it becomes “ghosted" or “greyed out" and doesn't respond to user input. For example, let's see how to cre- ate a component that can be used only once. This requires getting ahead of the story; we won't ex- plain some aspects of this ex- ample until later. Earlier, we said that a JButton generates an Ac- tionEvent when it is pressed. This event is delivered to the listeners' actionPer formed( ) method. The following code dis- ables the component that gener- ated the event: public boolean void action ((JComponent )e. getSour t This code calls getSource() to find out which component gener- ated the event. We cast the result to JComponent because we don't necessarily know what kind of component we're dealing with; it might not be a button, because other kinds of components can generate action events. Once we know which component generated the event, we disable it. You can also disable an entire container. Disabling a JPanel, for instance, disables all the compon- ents it contains. Other Component Methods The JComponent class is very large; it has to provide the base- level functionality for all the vari- ous kinds of Java GUI objects. It inherits a lot of functionality from its parent Container and Com- ponent classes. We don't have room to document every method of the JComponent class here, but we'll flesh out our discussion by covering some of the more im- portant ones: Container getParent() String getName() void setName(String name ) Get or assign the String name of this component. Naming component. Naming a component is use- ful for debugging. The name is returned by toString(). void setVisible(boolean visible) Make the component visible or invisible within its container. If you change the component's visibility, the container's layout manager automatic- ally lays out its vis- ible components. Color getForeground() void setForeground(Color c) Cc) void setBackground(Color Cc) Color getBackground( ) Get and set the fore- ground and back- ground colors for this component. The foreground color of any component is the default color used for drawing. For example, it is the color used for text in a text field as well as the default drawing color for the Graph- ics object passed to the component's paint() and paintComponent() methods. The back- ground color is used ground color is used to fill the component's area when it is cleared by the default imple- mentation of update(). Dimension getSize() void setSize(int width, int height) Get and set the cur- rent size of the component. Note that a layout man- ager may change the size of a component even after you've set its size yourself. To change the size a component "wants" to be, use setPreferredSize(). There are other mathacde in Ifam If you change a component's pre- ferred size, you must call the method revalidate() on the component to get it laid out again. Cursor getCursor() void setCursor (Cursor cursor) Get or set the type of cursor (mouse pointer) used when the mouse is over this component's area. For example: JComponent myComponent Cursor crossHairs = Cursor.getPredefinedCu myComponent.setCursor( cro Z-Ordering (Stacking Components) 10 With the standard layout managers, components are not al- lowed to overlap. However, if you use custom-built layout managers or absolute positioning, compon- ents within a container may overlap. If they do, the order in which components were added to a container matters. When com- ponents overlap, they are “stacked” in the order in which they were added: the first com- ponent added to the container is on top, and the last is on the bottom. To give you more control over stacking, two additional forms of the add( ) method take an extra integer argument that lets you specify the component's exact position in the container's stacking order. Again, you don't Managing Components There are a few additional tools of the Container class we should mention: Component[] getComponents() Returns the container's compon- ents in an array. void list(Printwriter out, int indent) Generates a list of the components in this container and writes them to the specified PrintWriter. Component getComponentAt (int getComponentAt (int x, int y) Tells you what com- ponent is at the spe- cified coordinates in the container's co- ordinate system. Listening for Components You can use the ContainerL- istener interface to automate setting up a container's new components. A container that im- plements this interface can re- ceive an event whenever it gains or loses a component. This facility makes it easy for a container to micromanage its components. e Navigate to a URI with the de- fault browser e Launch the default mail client and populate the "To:" field e Open, edit, or print a file utiliz- ing its associated application The Desktop class has a very simple API. The following ex- ample opens the default browser and navigates to the Duke Lemur Center's home page. //file: DisplayLemur. java import java.awt.*; import java.io.*; import java.net.*; public class DisplayLemur public static void mai URI uri = null; try { uri = new URI( Desktop. getDes } catch(IOExceptio System.out.pri } catch(URISyntaxE System.out.pri Component 1 6 Container Button Label Checkbox Choice Scrollbar Window Panel / ™. Frame Dialog Event Handling Event handling is fundamental to Java programming because it is used to create event driven programs eg Applets GUI based windows application Web Application Event handling mechanism have been changed significantly between the original version of Java (1.0) and all subsequent versions of Java, beginning with version 1.1. The modern approach to handling events is based on the delegation event model, Types of Event The events can be broadly classified into two categories: Foreground Events - Those events which require the direct interaction of user.They are generated as consequences of a person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc. Background Events - Those events that require the interaction of end user are known as background events. Operating system interrupts, hardware or software failure, timer expires, an operation completion are the example of background events. 19 Advantages of event Handling The benefit of this approach is that the user interface logic is completely separated from the logic that generates the event. The user interface element is able to delegate the processing of an event to the separate piece of code. In this model ,Listener needs to be registered with the source object so that the listener can receive the event notification. This is an efficient way of handling the event because the event notifications are sent only to those listener that want to receive them. Java Event classes and Listener interfaces 2 0 ActionEvent ActionListener MouseEvent MouseListener and MouseMotionListener MouseWheelEvent | MouseWheelListener KeyEvent KeyListener ltemEvent ltemListener TextEvent TextListener AdjustmentEvent —— AdjustmentListener WindowEvent WindowListener ComponentEvent —— ComponentListener | en Components of Event Handling Event handling has three main 71 components, e Events: An event is a change in state of an object. ¢ Events Source: An event source is an object that generates an event. e Listeners: A listener is an object that listens to the event. A listener gets notified when an event occurs. Steps to handle events: ¢ Implement appropriate interface in the class. e Register the component with the listener. Example of Event Handling import import *k- import import import *k: import public java.awt.*; java.awt.event. java.applet.*; java.applet.*; java.awt.event. java.awt.*; class Test exten ds Applet implements Ke Listener tring public msg="; void init() public void init() 23 { addKeyListener(thi S)5 } public void keyPressed (KeyEvent k) { showStatus("KeyPress ed"); } public void keyReleased (KeyEvent k) { showStatus("KeyReal esed"); } ublic void keyTyped( a k) msg = msget+k.getKeyChar msg = msgt+k.getKeyChar QO; repaint(); 274 } public void paint(Graph ics g) { g.drawString(msg, 2 0, 40); } } HTML code: 20 EVENT SOURCE Os ic Registers Listener C=) an Event C=) EVENT LISTENER @) Reacts to the Event We cHindiStudy Visit event handling in java hindi with What is ‘Threads’? 26 Threads can help us to do parallel processing. Threads are useful when you want to run multiple pieces of code in parallel. A thread can be defined as a lightweight process which can execute multiple codes in parallel. However, the thread is different from a process. In OS, for each process, a separate memory will be allocated. And the same is applicable for thread as well, it has separate memory. All the threads will run in the same memory which is allogated. for the process. A Thread can be created in Java in the following ways: 2 7 1. By Extending Thread class 2. Implementing Runnable interface By extending Thread class: public class PlayMusic extends Thread { public void run() { for(int 1=0;1<1000;i++) { System.out.println( "Music Playing ...... "); } S public static void main(String Args[]) 28 PlayMusic p=new PlayMusic(); p.start(); for(int i=0;1<1000;i++) { System.out.println("coding"); } } } Thread Methods: startQ — Starts the thread. 2 9 getState() — It returns the state of the thread. getName() - It returns the name of the thread. getPriority( — It returns the priority of the thread. sleepQ - Stop the thread for the specified time. JoinQ - Stop the current thread until the called thread gets terminated. isAliveQ — Check if the thread is alive. Thread Lifecycle: Threads can go through five different status in its life cycle as shown below. 3 0 1. New: When the thread instance is created, it will be in “New?” state. 2. Runnable: When the thread is started, it is called “Runnable” state. 3. Running: When the thread is running, it is called “Running” state. 4. Waiting: When the thread is put on hold or it is waiting for the other thread to complete, then that state will be known as “waiting” state. 5. Terminated: When the thread is dead, it will be known as “terminated” state. public class ThreadMethodsDemo extends Thread { public void run() { for(int i=0;i<10;it+) { System.out.println( "thread methods demo"); try { System.out.println( "thread is going to sleep"); ThreadMethodsDemo. sleep( 1000) ; System.out.println("thread wake up"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); t 32 } public static void main(String[] args) throws InterruptedException { ThreadMethodsDemo de = new ThreadMethodsDemo(); System.out.println("getstate1"+ Runnable state de.start(); System.out.println("getstate2"+ System.out.println("getstate3"+ System.out.println("getstate4"+ System.out.println("thread Name"+de.getName()); System.out.printlin("thread Priority"+de.getPriority()); System.out.println("getstate5"+ ) oo Key Points to be noted: e To execute multiple codes in parallel, we are going for threads. 3 4 e You can create threads in two ways. Extending thread class and Implementing Runnable interface. e Thread status is new, runnable, running, waiting, and terminated. wail) Blocked Newborn > Rumabie > stop() stop() Cdad> We CSE UT Kgp CHAPTER 6 --Threads and Multithreading in Java notiéy ) resume() Running yield() stop() Visit Features Of Computer network digram Mari poodathiga d... point Mari poottu aluthuga communication speed a Network provides us to communicate over network in a fast and efficient manner. For example, we can do video conferencing, email messaging, etc. over the internet. Therefore, the computer network is a great way to share our knowledge and ideas. file sharing File sharing is one of the major advantage of the computer network. Computer network provides us to share the files with each other. Back up and Roll back is easy 38 Since the files are stored in the main server which is centrally located. Therefore, it is easy to take the back up from the main server. Software and Hardware sharing We can install the applications on the main server, therefore, the user can access the applications centrally. So, we do not need to install the software on every machine. Similarly, hardware can also be shared. Security 3 9 Network allows the security by ensuring that the user has the right to access the certain files and applications. Scalability Scalability means that we can add the new components on the network. Network must be scalable so that we can extend the network by adding new devices. But, it decreases the speed of the connection and data of the transmission speed also decreases, this increases the chances of error occurring. This problem can be overcome by using the routing or switching devices. Reliability 4 0 Computer network can use the alternative source for the data communication in case of any hardware failure. Beginnenbook.com Performance Data Sharing Backup Features of Computer network pelo Security Scalability 4] Software & hardware compatibility oO BeginnersBook. com Computer Network Features Visit Introduction to Java media programming Learn the basics of Java-based multimedia with the Java Media and Communication APIs ©O0600 Java as a versatile programming language has gained widespread acceptance in the two-plus years since its introduction. It is widely espoused as having the usual benefits with which we are all familiar: cross-platform portability, a fairly secure runtime environment, strong networking and connectivity APIs, and so on. History of media support (or lack thereof) in Java 43 Historically, Java has provided weak support for multimedia. The JDK 1.0 and JDK 1.1 core platform releases provided minimal support for sound in applets and no official support of sound in applications. In addition, Sun provided no support for video manipulation, streaming media capture or playback, 2D or 3D graphics (except through the use of basic drawing primitives), or numerous other advanced multimedia services. Java Platform 1.0 (1995 initial release) 1.1 (1997 release) 1.2 (September 1998) Availability All browsers, OSs, IDEs (wide availability) Some browsers, OSs, IDEs (still has problems one year later) Not yet released (no availability except beta from Sun) Media support Primitive 2D (AWT); limited audio (applets only); no video, 3D, telephony, or speech Same as 1.0 release 44 Adds Java 2D, Java Sound Engine; still no built in video, 3D, telephony, or speech The Java Media and Communication APls There are a number of APIs that fall within the purview of media and communications. These, and what they enable in the Java platform, include: 45 e Java 2D -- 2D graphics and image manipulation Java 3D -- 3D graphics runtime Java Media Framework -- playback of synchronized media Java Sound -- software sound processor and MIDI synthesizer 46 Java Speech -- speech recognition and synthesis Java Telephony -- computer and telephony integration blatant request for input As always, please let me know about topics you want covered. | appreciate any ideas or comments you care to share. | hope this column will provide you with useful information and ideas for the development of media-rich applications. Content Continues Below 47 Bill Day is a software engineer at Silicon Graphics Computer Systems. In addition to writing for JavaWorld, Bill is authoring a book entitled Java Media Players for O'Reilly & Associates. When Bill is not writing or

You might also like