Java mobile development tools

java development environment tools and java desktop application development tools
JohenCorner Profile Pic
Published Date:02-08-2017
Your Website URL(Optional)
A First Application Before diving into our full discussion of the Java language, let’s get our feet wet by jumping into some working code and splashing around a bit. In this chapter, we’ll build a friendly little application that illustrates many of the concepts used throughout the book. We’ll take this opportunity to introduce general features of the Java language and applications. This chapter also serves as a brief introduction to the object-oriented and multithreaded aspects of Java. If these concepts are new to you, we hope that encountering them here in Java for the first time will be a straightforward and pleasant experience. If you have worked with another object-oriented or multithreaded programming environment, you should especially appreciate Java’s simplicity and elegance. This chapter is intended only to give you a bird’s eye view of the Java language and a feel for how it is used. If you have trouble with any of the concepts introduced here, rest assured they will be covered in greater detail later in the book. We can’t stress enough the importance of experimentation as you learn new concepts here and throughout the book. Don’t just read the examples—run them. The source code for these examples and all of the examples in this book can be found on our website. Compile the programs and try them. Then, turn our examples into your ex‐ amples: play with them, change their behavior, break them, fix them, and hopefully have some fun along the way. Java Tools and Environment Although it’s possible to write, compile, and run Java applications with nothing more than Oracle’s Java Development Kit (JDK) and a simple text editor (e.g., vi, Notepad, etc.), today the vast majority of Java code is written with the benefit of an Integrated Development Environment (IDE). The benefits of using an IDE include an all-in-one view of Java source code with syntax highlighting, navigation help, source control, 25 a integrated documentation, building, refactoring, and deployment all at your fingertips. Therefore, we are going to skip an academic command-line treatment and start with the most popular IDE, Eclipse. If you are adverse to using an IDE, feel free to use the command-line instructions javac for compilation and java Hello Java to run the upcoming examples. IBM originally spearheaded The Eclipse Project in 2001, leading a consortium of soft‐ ware vendors to create an open and extensible development environment to rival the then-legendary Visual Studio environment from Microsoft. Today, Eclipse has grown into a powerful open source platform supported by individuals and corporations alike, backed by a thriving ecosystem of plug-ins and frameworks. Although Java is the most popular language associated with Eclipse, the IDE supports dozens of languages. We will be doing a light introduction to Eclipse in this chapter. For a more comprehensive approach, see Appendix A. Eclipse requires a Java Runtime Environment (JRE) to be installed. This book covers Java 7 language features, so although the examples in this chapter will work with older versions, it’s best to have JDK 7 installed to ensure that all examples in the book compile. The JDK includes the JRE as well as developer tools. You can check to see which version, if any, you have installed by typing java -version at the command line. If Java isn’t present, or if it’s a version older than JDK 7 (confusingly also referred to as JDK 1.7), you will want to download the latest version from Oracle’s download page. All that is required for the examples in this book is the basic JDK, which is the first option in the upper-left corner of the download page. Eclipse is an open source IDE available at For the purposes of this book, and getting started with Java in general, the Eclipse Classic download is sufficient. Make sure the architecture of your JDK and Eclipse matches. In other words, don’t use a 64- bit JDK with a 32-bit version of Eclipse or vice versa. The download is a compressed archive: .zip for Windows and .tar.gz on OS X and Linux. Double-click to expand and run the installer. Configuring Eclipse and Creating a Project The first time you run Eclipse, you’ll be prompted to select a workspace. This is a root directory to hold new projects that you create within Eclipse. The default location is inside the application’s folder itself, which is probably not what you want. Choose a location and click OK. Eclipse greets you with the Welcome screen. Close this window by closing the Welcome tab within the application. If you want to come back later and go through the Eclipse tutorials and related help topics, you can return to this window by choosing Help→ Welcome. 26 Chapter 2: A First Application a One last thing before we move on: Eclipse stores all of its configuration information in the configuration folder inside the Eclipse installation directory. If, at any point in this introduction, you feel that things are not right and you want to start from scratch, you can quit the application and remove this folder. You may also wish to remove your workspace items as they hold per-project state. Less drastically, if you wish to reset all of the application windows to their default locations, you can choose Window→ Reset Perspective. We’ll talk more about perspectives later. We are going to create a project to hold all our examples. Select File→ New→ Java Project from the application menu and type Learning Java in the “Project name” field at the top of the dialog, as seen in Figure 2-1. Make sure the JRE version is set to JavaSE-1.7 as seen in the figure and click Next at the bottom. Figure 2-1. New Java Project dialog Configuring Eclipse and Creating a Project 27 a Next, you will need to set your build path to the Java 7 system library. Select the Libra‐ ries tab and remove the Java 1.6 library. Click Add Library and select JavaSE-1.7. Eclipse is now configured to use Java 7. Click Finish. Importing the Learning Java Examples Let’s load the examples from this book. You can find a ZIP file containing all of the examples from this book nicely packaged as an Eclipse project at Java_4E. The Eclipse version of the examples is called (The file holds the same examples but packaged slightly differently and without the Eclipse project files.) Next, we’ll import the examples ZIP file. Choose File→ Import to open the Import wizard. Select Archive File as the source and click Next. See Figure 2-2. Figure 2-2. New Java Project dialog Click the Browse button and choose the file as seen in Figure 2-3. Check the “Overwrite existing resources without warning” button so that our Eclipse- specific project file will overwrite the empty one in your new project. Click Finish. 28 Chapter 2: A First Application aFigure 2-3. New Java Project dialog Eclipse will now import all of the files from the archive and immediately begin building the source in the background (a small progress bar at the bottom of the screen will show this). On the left is the Package Explorer. It shows a tree view of the Java packages, libraries, and resources of our project. Click the folder handles to expand the tree and see source folders for each chapter in the book. Now we are ready to start coding HelloJava In the tradition of introductory programming texts, we will begin with Java’s equivalent of the archetypal “Hello World” application,HelloJava. We’ll end up taking four passes at this example before we’re done (HelloJava, Hello Java2, etc.), adding features and introducing new concepts along the way. But let’s start with the minimalist version: public class HelloJava public static void main( String args ) System.out.println("Hello, Java"); This five-line program declares a class calledHelloJava and a method calledmain() . It uses a predefined method called println() to write some text as output. This is a HelloJava 29 a command-line program, which means that it runs in a shell or DOS window and prints its output there. That’s a bit old-school for our taste, so before we go any further, we’re going to give HelloJava a graphical user interface (GUI). Don’t worry about the code yet; just follow along with the progression here, and we’ll come back for explanations in a moment. In place of the line containing theprintln() method, we’re going to use aJFrame object to put a window on the screen. We can start by replacing the println line with the following three lines: JFrame frame = new JFrame( "Hello, Java" ); frame.setSize( 300, 300 ); frame.setVisible( true ); This snippet creates aJFrame object with the title “Hello, Java” TheJFrame is a graphical window. To display it, we simply configure its size on the screen using the setSize() method and make it visible by calling thesetVisible() method. If we stopped here, we would see an empty window on the screen with our “Hello, Java” banner as its title. We’d like our message inside the window, not just scrawled at the top of it. To put something in the window, we need a couple more lines. The following complete example adds aJLabel object to display the text centered in our window. The additional import line at the top is necessary to tell Java where to find the JFrame and JLabel classes (the definitions of theJFrame andJLabel objects that we’re using). import javax.swing.; public class HelloJava public static void main( String args ) JFrame frame = new JFrame( "Hello, Java" ); JLabel label = new JLabel("Hello, Java", JLabel.CENTER ); frame.add(label); frame.setSize( 300, 300 ); frame.setVisible( true ); Now to compile and run this source, select the ch02/ class from the pack‐ age explorer along the left and click the Run button in the toolbar along the top. The Run button is a green circle with a white arrow pointing to the right. See Figure 2-4. 30 Chapter 2: A First Application aFigure 2-4. Running the HelloJava application You should see the proclamation shown in Figure 2-5. Congratulations, you have run your first Java application Take a moment to bask in the glow of your monitor. Figure 2-5. The output of the HelloJava application Be aware that when you click on the window’s close box, the window goes away, but your program is still running. (We’ll fix this shutdown behavior in a later version of the example.) To stop the Java application in Eclipse, click the big red button in the console window. If you are running the example on the command line, type Ctrl-C. Note that HelloJava 31 a nothing stops you from running more than one instance (copy) of the application at a time. HelloJava may be a small program, but there is quite a bit going on behind the scenes. Those few lines represent the tip of an iceberg. What lies under the surface are the layers of functionality provided by the Java language and its foundation class libraries. Re‐ member that in this chapter, we’re going to cover a lot of ground quickly in an effort to show you the big picture. We’ll try to offer enough detail for a good understanding of what is happening in each example, but will defer detailed explanations until the ap‐ propriate chapters. This holds for both elements of the Java language and the object- oriented concepts that apply to them. With that said, let’s take a look now at what’s going on in our first example. Classes The first example defines a class namedHelloJava. public class HelloJava ... Classes are the fundamental building blocks of most object-oriented languages. A class is a group of data items with associated functions that can perform operations on that data. The data items in a class are called variables, or sometimes fields; in Java, functions are called methods. The primary benefits of an object-oriented language are this asso‐ ciation between data and functionality in class units and also the ability of classes to encapsulate or hide details, freeing the developer from worrying about low-level details. In an application, a class might represent something concrete, such as a button on a screen or the information in a spreadsheet, or it could be something more abstract, such as a sorting algorithm or perhaps the sense of ennui in a video game character. A class representing a spreadsheet might, for example, have variables that represent the values of its individual cells and methods that perform operations on those cells, such as “clear a row” or “compute values.” Our HelloJava class is an entire Java application in a single class. It defines just one method,main() , which holds the body of our program: public class HelloJava public static void main( String args ) ... It is thismain() method that is called first when the application is started. The bit labeled String args allows us to pass command-line arguments to the application. We’ll walk through the main() method in the next section. Finally, we’ll note that although this version of HelloJava does not define any variables as part of its class, it does use two variables,frame andlabel, inside itsmain() method. We’ll have more to say about variables soon as well. 32 Chapter 2: A First Application aThe main() Method As we saw when we ran our example, running a Java application means picking a par‐ ticular class and passing its name as an argument to the Java virtual machine. When we did this, the java command looked in our HelloJava class to see if it contained the special method namedmain() of just the right form. It did, and so it was executed. If it had not been there, we would have received an error message. The main() method is the entry point for applications. Every standalone Java application includes at least one class with a main() method that performs the necessary actions to start the rest of the program. Our main() method sets up a window (a JFrame) to hold the visual output of the HelloJava class. Right now, it’s doing all the work in the application. But in an object- oriented application, we normally delegate responsibilities to many different classes. In the next incarnation of our example, we’re going to perform just such a split—creating a second class—and we’ll see that as the example subsequently evolves, the main() method remains more or less the same, simply holding the startup procedure. Let’s quickly walk through our main() method, just so we know what it does. First, main() creates aJFrame, the window that will hold our example: JFrame frame = new JFrame("Hello, Java"); The word new in this line of code is very important. JFrame is the name of a class that represents a window on the screen, but the class itself is just a template, like a building plan. The new keyword tells Java to allocate memory and actually create a particular JFrame object. In this case, the argument inside the parentheses tells the JFrame what to display in its title bar. We could have left out the “Hello, Java” text and used empty parentheses to create a JFrame with no title, but only because the JFrame specifically allows us to do that. When frame windows are first created, they are very small. Before we show the JFrame, we set its size to something reasonable: frame.setSize( 300, 300 ); This is an example of invoking a method on a particular object. In this case, the set Size() method is defined by theJFrame class, and it affects the particularJFrame object we’ve placed in the variable frame. Like the frame, we also create an instance of JLa bel to hold our text inside the window: JLabel label = new JLabel("Hello, Java", JLabel.CENTER ); JLabel is much like a physical label. It holds some text at a particular position—in this case, on our frame. This is a very object-oriented concept: using an object to hold some text, instead of simply invoking a method to “draw” the text and moving on. The ra‐ tionale for this will become clearer later. HelloJava 33 aNext, we have to place the label into the frame we created: frame.add( label ); Here, we’re calling a method named add()to place our label inside the JFrame. The JFrame is a kind of container that can hold things. We’ll talk more about that later. main()’s final task is to show the frame window and its contents, which otherwise would be invisible. An invisible window makes for a pretty boring application. frame.setVisible( true ); That’s the wholemain() method. As we progress through the examples in this chapter, it will remain mostly unchanged as theHelloJava class evolves around it. Classes and Objects A class is a blueprint for a part of an application; it holds methods and variables that make up that component. Many individual working copies of a given class can exist while an application is active. These individual incarnations are called instances of the class, or objects. Two instances of a given class may contain different data, but they always have the same methods. As an example, consider a Button class. There is only one Button class, but an appli‐ cation can create many differentButton objects, each one an instance of the same class. Furthermore, twoButton instances might contain different data, perhaps giving each a different appearance and performing a different action. In this sense, a class can be considered a mold for making the object it represents, something like a cookie cutter stamping out working instances of itself in the memory of the computer. As you’ll see later, there’s a bit more to it than that—a class can in fact share information among its instances—but this explanation suffices for now. Chapter 5 has the whole story on classes and objects. The term object is very general and in some other contexts is used almost interchange‐ ably with class. Objects are the abstract entities that all object-oriented languages refer to in one form or another. We will use object as a generic term for an instance of a class. We might, therefore, refer to an instance of theButton class as a button, aButton object, or, indiscriminately, as an object. Themain() method in the previous example creates a single instance of theJLabel class and shows it in an instance of theJFrame class. You could modifymain() to create many instances ofJLabel, perhaps each in a separate window. Variables and Class Types In Java, every class defines a new type (data type). A variable can be declared to be of this type and then hold instances of that class. A variable could, for example, be of type Button and hold an instance of theButton class, or of typeSpreadSheetCell and hold 34 Chapter 2: A First Application a a SpreadSheetCell object, just as it could be any of the simpler types, such as int or float, that represent numbers. The fact that variables have types and cannot simply hold any kind of object is another important feature of the language that ensures the safety and correctness of code. Ignoring the variables used inside themain() method for the moment, only one other variable is declared in our simple HelloJava example. It’s found in the declaration of themain() method itself: public static void main( String args ) Just like functions in other languages, a method in Java declares a list of variables that it accepts as arguments or parameters, and it specifies the types of those variables. In this case, the main method is requiring that when it is invoked, it be passed a list of String objects in the variable namedargs. TheString is the fundamental object rep‐ resenting text in Java. As we hinted earlier, Java uses the args parameter to pass any command-line arguments supplied to the Java virtual machine (VM) into your appli‐ cation. (We don’t use them here.) Up to this point, we have loosely referred to variables as holding objects. In reality, variables that have class types don’t so much contain objects as point to them. Class- type variables are references to objects. A reference is a pointer to or a handle for an object. If you declare a class-type variable without assigning it an object, it doesn’t point to anything. It’s assigned the default value ofnull, meaning “no value.” If you try to use a variable with a null value as if it were pointing to a real object, a runtime error, NullPointerException, occurs. Of course, object references have to come from somewhere. In our example, we created two objects using thenew operator. We’ll examine object creation in more detail a little later in the chapter. HelloComponent Thus far, our HelloJava example has contained itself in a single class. In fact, because of its simple nature, it has really just served as a single, large method. Although we have used a couple of objects to display our GUI message, our own code does not illustrate any object-oriented structure. Well, we’re going to correct that right now by adding a second class. To give us something to build on throughout this chapter, we’re going to take over the job of the JLabel class (bye bye, JLabel) and replace it with our own graphical class: HelloComponent. Our HelloComponent class will start simple, just dis‐ playing our “Hello, Java” message at a fixed position. We’ll add capabilities later. The code for our new class is very simple; we added just a few more lines: import java.awt.; class HelloComponent extends JComponent HelloJava 35 a public void paintComponent( Graphics g ) g.drawString( "Hello, Java", 125, 95 ); You can add this text to the file, or you can place it in its own file called If you put it in the same file, you must move the new import statement to the top of the file, along with the other one. To use our new class in place of theJLabel, simply replace the two lines referencing the label with: frame.add( new HelloComponent() ); This time when you compile, you will see two binary class files: Hello‐ Java.class and HelloComponent.class (regardless of how you arranged the source). Run‐ ning the code should look much like the JLabel version, but if you resize the window, you’ll notice that our class does not automatically adjust to center the code. So what have we done, and why have we gone to such lengths to insult the perfectly good JLabel component? We’ve created our new HelloComponent class, extending a generic graphical class calledJComponent. To extend a class simply means to add func‐ tionality to an existing class, creating a new one. We’ll get into that in the next section. Here we have created a new kind of JComponent that contains a method called paint Component(), which is responsible for drawing our message. Our paintComponent() method takes one argument named (somewhat tersely) g, which is of type Graphics. When the paintComponent() method is invoked, a Graphics object is assigned to g, which we use in the body of the method. We’ll say more aboutpaintComponent() and theGraphics class in a moment. As for why, you’ll understand when we add all sorts of new features to our new component later on. Inheritance Java classes are arranged in a parent-child hierarchy in which the parent and child are known as the superclass and subclass, respectively. We’ll explore these concepts fully in Chapter 6. In Java, every class has exactly one superclass (a single parent), but possibly many subclasses. The only exception to this rule is theObject class, which sits atop the entire class hierarchy; it has no superclass. The declaration of our class in the previous example uses the keywordextends to specify thatHelloComponent is a subclass of theJComponent class: public class HelloComponent extends JComponent ... A subclass may inherit some or all the variables and methods of its superclass. Through inheritance, the subclass can use those variables and methods as if it has declared them itself. A subclass can add variables and methods of its own, and it can also override or change the meaning of inherited methods. When we use a subclass, overridden methods are hidden (replaced) by the subclass’s own versions of them. In this way, inheritance 36 Chapter 2: A First Application aprovides a powerful mechanism whereby a subclass can refine or extend the function‐ ality of its superclass. For example, the hypothetical spreadsheet class might be subclassed to produce a new scientific spreadsheet class with extra mathematical functions and special built-in con‐ stants. In this case, the source code for the scientific spreadsheet might declare methods for the added mathematical functions and variables for the special constants, but the new class automatically has all the variables and methods that constitute the normal functionality of a spreadsheet; they are inherited from the parent spreadsheet class. This also means that the scientific spreadsheet maintains its identity as a spreadsheet, and we can use the extended version anywhere the simpler spreadsheet could be used. That last sentence has profound implications, which we’ll explore throughout the book. It means that specialized objects can be used in place of more generic objects, customizing their behavior without changing the underlying application. This is called polymor‐ phism and is one of the foundations of object-oriented programming. OurHelloComponent class is a subclass of theJComponent class and inherits many vari‐ ables and methods not explicitly declared in our source code. This is what allows our tiny class to serve as a component in aJFrame, with just a few customizations. The JComponent Class The JComponent class provides the framework for building all kinds of user interface components. Particular components—such as buttons, labels, and list boxes—are im‐ plemented as subclasses ofJComponent. We override methods in such a subclass to implement the behavior of our particular component. This may sound restrictive, as if we are limited to some predefined set of routines, but that is not the case at all. Keep in mind that the methods we are talking about are ways to interact with the windowing system. We don’t have to squeeze our whole application in there. A realistic application might involve hundreds or thousands of classes, with legions of methods and variables and many threads of execution. The vast majority of these are related to the particulars of our job (these are called domain objects). TheJComponent class and other predefined classes serve only as a framework on which to base code that handles certain types of user interface events and displays information to the user. The paintComponent() method is an important method of the JComponent class; we override it to implement the way our particular component displays itself on the screen. The default behavior of paintComponent() doesn’t do any drawing at all. If we hadn’t overridden it in our subclass, our component would simply have been invisible. Here, we’re overridingpaintComponent() to do something only slightly more interesting. We don’t override any of the other inherited members ofJComponent because they provide basic functionality and reasonable defaults for this (trivial) example. As HelloJava grows, we’ll delve deeper into the inherited members and use additional methods. We HelloJava 37 a will also add some application-specific methods and variables specifically for the needs ofHelloComponent. JComponent is really the tip of another iceberg called Swing. Swing is Java’s user interface toolkit, represented in our example by the import statement at the top; we’ll discuss it in some detail in Chapters 16 through 18. Relationships and Finger Pointing We can correctly refer toHelloComponent as aJComponent because subclassing can be thought of as creating an “is a” relationship, in which the subclass “is a” kind of its superclass.HelloComponent is therefore a kind ofJComponent. When we refer to a kind of object, we mean any instance of that object’s class or any of its subclasses. Later, we will look more closely at the Java class hierarchy and see that JComponent is itself a subclass of the Container class, which is further derived from a class called Compo nent, and so on, as shown in Figure 2-6. In this sense, a HelloComponent object is a kind of JComponent, which is a kind of Container, and each of these can ultimately be considered to be a kind of Component. It’s from these classes thatHelloComponent inherits its basic GUI functionality and (as we’ll discuss later) the ability to have other graphical components embedded within it as well. Figure 2-6. Part of the Java class hierarchy Component is a subclass of the top-level Object class, so all these classes are types of Object. Every other class in the Java API inherits behavior fromObject, which defines a few basic methods, as you’ll see in Chapter 7. We’ll continue to use the word object 38 Chapter 2: A First Application a (lowercase o) in a generic way to refer to an instance of any class; we’ll use Object to refer specifically to the type of that class. Package and Imports We mentioned earlier that the first line of our example tells Java where to find some of the classes that we’ve been using: import javax.swing.; Specifically, it tells the compiler that we are going to be using classes from the Swing GUI toolkit (in this case,JFrame,JLabel, andJComponent). These classes are organized into a Java package called javax.swing. A Java package is a group of classes that are related by purpose or by application. Classes in the same package have special access privileges with respect to one another and may be designed to work together closely. Packages are named in a hierarchical fashion with dot-separated components, such as java.util and Classes in a package must follow conventions about where they are located in the classpath. They also take on the name of the package as part of their “full name” or, to use the proper terminology, their fully qualified name. For example, the fully qualified name of the JComponent class is javax.swing.JCompo nent. We could have referred to it by that name directly, in lieu of using the import statement: public class HelloComponent extends javax.swing.JComponent ... The statement import javax.swing. enables us to refer to all the classes in the jav ax.swing package by their simple names. So we don’t have to use fully qualified names to refer to theJComponent,JLabel, andJFrame classes. As we saw when we added our second example class, there may be one or more im port statements in a given Java source file. Theimports effectively create a “search path” that tells Java where to look for classes that we refer to by their simple, unqualified names. (It’s not really a path, but it avoids ambiguous names that can create errors.) The im ports we’ve seen use the dot star (.) notation to indicate that the entire package should be imported. But you can also specify just a single class. For example, our current ex‐ ample uses only theGraphics class from thejava.awt package. So we could have used import java.awt.Graphics instead of using the wildcard to import all the Abstract Window Toolkit (AWT) package’s classes. However, we are anticipating using several more classes from this package later. The java. and javax. package hierarchies are special. Any package that begins with java. is part of the core Java API and is available on any platform that supports Java. Thejavax. package normally denotes a standard extension to the core platform, which may or may not be installed. However, in recent years, many standard extensions have been added to the core Java API without renaming them. Thejavax.swing package is HelloJava 39 a an example; it is part of the core API in spite of its name. Figure 2-7 illustrates some of the core Java packages, showing a representative class or two from each. Figure 2-7. Some core Java packages java.lang contains fundamental classes needed by the Java language itself; this package is imported automatically and that is why we didn’t need an import statement to use class names such asString orSystem in our examples. Thejava.awt package contains classes of the older, graphical Abstract Window Toolkit; contains the net‐ working classes; and so on. As you gain more experience with Java, you will come to realize that having a command of the packages available to you, what they do, when to use them, and how to use them is a critical part of becoming a successful Java developer. The paintComponent() Method The source for our HelloComponent class defines a method, paintComponent(), that overrides thepaintComponent() method of theJComponent class: public void paintComponent( Graphics g ) g.drawString( "Hello, Java", 125, 95 ); The paintComponent() method is called when it’s time for our example to draw itself on the screen. It takes a single argument, aGraphics object, and doesn’t return any type of value (void) to its caller. 40 Chapter 2: A First Application a Modifiers are keywords placed before classes, variables, and methods to alter their ac‐ cessibility, behavior, or semantics. paintComponent() is declared as public, which means it can be invoked (called) by methods in classes other thanHelloComponent. In this case, it’s the Java windowing environment that is calling our paintComponent() method. A method or variable declared asprivate is accessible only from its own class. TheGraphics object, an instance of theGraphics class, represents a particular graphical drawing area. (It is also called a graphics context.) It contains methods that can be used to draw in this area, and variables that represent characteristics such as clipping or drawing modes. The particular Graphics object we are passed in the paintCompo nent() method corresponds to our HelloComponent’s area of the screen, inside our frame. TheGraphics class provides methods for rendering shapes, images, and text. InHello Component, we invoke thedrawString() method of ourGraphics object to scrawl our message at the specified coordinates. (For a description of the methods available in the Graphics class, see Chapter 20.) As we’ve seen earlier, we access a method of an object by appending a dot (.) and its name to the object that holds it. We invoked the drawString() method of the Graph ics object (referenced by ourg variable) in this way: g.drawString( "Hello, Java", 125, 95 ); It may be difficult to get used to the idea that our application is drawn by a method that is called by an outside agent at arbitrary times. How can we do anything useful with this? How do we control what gets done and when? These answers are forthcoming. For now, just think about how you would begin to structure applications that respond on command instead of by their own initiative. HelloJava2: The Sequel Now that we’ve got some basics down, let’s make our application a little more interactive. The following minor upgrade allows us to drag the message text around with the mouse. We’ll call this exampleHelloJava2 rather than cause confusion by continuing to expand the old one, but the primary changes here and further on lie in adding capabilities to theHelloComponent class and simply making the corresponding changes to the names to keep them straight (e.g., HelloComponent2, HelloComponent3, and so on). Having just seen inheritance at work, you might wonder why we aren’t creating a subclass of HelloComponent and exploiting inheritance to build upon our previous example and extend its functionality. Well, in this case, that would not provide much advantage, and for clarity we simply start over. Here isHelloJava2: HelloJava2: The Sequel 41 a //file: import java.awt.; import java.awt.event.; import javax.swing.; public class HelloJava2 public static void main( String args ) JFrame frame = new JFrame( "HelloJava2" ); frame.add( new HelloComponent2("Hello, Java") ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setSize( 300, 300 ); frame.setVisible( true ); class HelloComponent2 extends JComponent implements MouseMotionListener String theMessage; int messageX = 125, messageY = 95; // Coordinates of the message public HelloComponent2( String message ) theMessage = message; addMouseMotionListener(this); public void paintComponent( Graphics g ) g.drawString( theMessage, messageX, messageY ); public void mouseDragged(MouseEvent e) // Save the mouse coordinates and paint the message. messageX = e.getX(); messageY = e.getY(); repaint(); public void mouseMoved(MouseEvent e) Two slashes in a row indicate that the rest of the line is a comment. We’ve added a few comments toHelloJava2 to help you keep track of everything. Place the text of this example in a file called and compile it as before. You should get new class files, HelloJava2.class and HelloComponent2.class, as a result. Run the example using the following command: C:\ java HelloJava2 42 Chapter 2: A First Application a Or, if you are following in Eclipse, click the Run button. Feel free to substitute your own salacious comment for the “Hello, Java” message and enjoy many hours of fun, dragging the text around with your mouse. Notice that now when you click the window’s close button, the application exits; we’ll explain that later when we talk about events. Now let’s see what’s changed. Instance Variables We have added some variables to theHelloComponent2 class in our example: int messageX = 125, messageY = 95; String theMessage; messageX andmessageY are integers that hold the current coordinates of our movable message. We have crudely initialized them to default values that should place the mes‐ sage somewhere near the center of the window. Java integers are 32-bit signed numbers, so they can easily hold our coordinate values. The variabletheMessage is of typeString and can hold instances of theString class. You should note that these three variables are declared inside the braces of the class definition, but not inside any particular method in that class. These variables are called instance variables, and they belong to the class as a whole. Specifically, copies of them appear in each separate instance of the class. Instance variables are always visible to (and usable by) all the methods inside their class. Depending on their modifiers, they may also be accessible from outside the class. Unless otherwise initialized, instance variables are set to a default value of0,false, or null, depending on their type. Numeric types are set to0, Boolean variables are set to false, and class type variables always have their value set to null, which means “no value.” Attempting to use an object with anull value results in a runtime error. Instance variables differ from method arguments and other variables that are declared inside the scope of a particular method. The latter are called local variables. They are effectively private variables that can be seen only by code inside the method. Java doesn’t initialize local variables, so you must assign values yourself. If you try to use a local variable that has not yet been assigned a value, your code generates a compile-time error. Local variables live only as long as the method is executing and then disappear, unless something else saves their value. Each time the method is invoked, its local variables are recreated and must be assigned values. We have used the new variables to make our previously stodgy paintComponent() method more dynamic. Now all the arguments in the call to drawString() are deter‐ mined by these variables. HelloJava2: The Sequel 43 aConstructors TheHelloComponent2 class includes a special kind of a method called a constructor. A constructor is called to set up a new instance of a class. When a new object is created, Java allocates storage for it, sets instance variables to their default values, and calls the constructor method for the class to do whatever application-level setup is required. A constructor always has the same name as its class. For example, the constructor for theHelloComponent2 class is calledHelloComponent2(). Constructors don’t have a re‐ turn type, but you can think of them as creating an object of their class’s type. Like other methods, constructors can take arguments. Their sole mission in life is to configure and initialize newly born class instances, possibly using information passed to them in these parameters. An object is created with the new operator specifying the constructor for the class and any necessary arguments. The resulting object instance is returned as a value. In our example, a newHelloComponent2 instance is created in themain() method by this line: frame.add( new HelloComponent2("Hello, Java") ); This line actually does two things. We could write them as two separate lines that are a little easier to understand: HelloComponent2 newObject = new HelloComponent2("Hello, Java"); frame.add( newObject ); The first line is the important one, where a newHelloComponent2 object is created. The HelloComponent2 constructor takes aString as an argument and, as we have arranged it, uses it to set the message that is displayed in the window. With a little magic from the Java compiler, quoted text in Java source code is turned into a String object. (See Chapter 10 for a complete discussion of theString class.) The second line simply adds our new component to the frame to make it visible, as we did in the previous examples. While we’re on the topic, if you’d like to make our message configurable, you can change the constructor line to the following: HelloComponent2 newobj = new HelloComponent2( args0 ); Now you can pass the text on the command line when you run the application using the following command: C:\ java HelloJava2 "Hello, Java" args0 refers to the first command-line parameter. Its meaning will become clearer when we discuss arrays later in the book. If you are using an IDE, such as Eclipse, you will need to configure it to accept your parameters before running it. HelloComponent2’s constructor then does two things: it sets the text of theMessage instance variable and callsaddMouseMotionListener(). This method is part of the event 44 Chapter 2: A First Application a

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.