Sunday, February 28, 2010

console input

JDK 5.0 provides a feature to read input from console. Java.util,Scanner is used for this purpose. This code read a String and an Integer from the console and stores them in the variables.


http://www.java-tips.org/java-se-tips/java.util/how-to-read-input-from-console.html

import java.util.Scanner;

public class InputExp {

public static void main(String[] args) {

String name;
int age;
Scanner in = new Scanner(System.in);

// Reads a single line from the console
// and stores into name variable
name = in.nextLine();

// Reads a integer from the console
// and stores into age variable
age=in.nextInt();
in.close();

// Prints name and age to the console
System.out.println("Name :"+name);
System.out.println("Age :"+age);

}
}

Wednesday, February 24, 2010

How To Use Command Line Arguments in Eclipse

Colorado State University

How To Use Command Line Arguments in Eclipse



LINKS INTO DOCUMENT BELOW
Introduction Detailed Instructions using Welcome.java
Instructions using Args.java Instructions using TempConversion.java


http://www.cs.colostate.edu/helpdocs/eclipseCommLineArgs.html

How To Use Command Line Arguments in Eclipse

The main example used in these notes is the Welcome class,
developed in the WelcomeToJava Eclipse project.

This program accepts one input argument value,
which is automatically assigned to the first value
in String[] args, called args[0].
(Computer people tend to count from 0 and not 1.)

Study the program for a few minutes to find where args[0] is used.
Notice that it is of type String.

The detailed instructions are in the next section,
complete with screenshots from the Welcome class in Eclipse.

Two other example programs are described in the last section.


Detailed Instructions for Command Line Arguments in Eclipse
Example: Welcome.java

  1. Basically, it's simple.
    Click on Run -> Run (not Run Last Launched).

    In the window shown below,
    notice that the Welcome Java application is highlighted.

    In the large subwindow of the Run window, there is a set of tabs,
    labelled Main, Arguments, JRE, etc.
    Notice that the Main tab is highlighted.

  2. Click on the Arguments tab.
    This action brings up a window
    with a few places to enter values.
    You want to type in all your input values
    into the Program arguments window,
    with spaces (blank characters) between each value.

    For the Welcome program,
    only one input argument value is needed:
    the first name of a new Java student.
    For this run, we have chosen Sarah as
    the name of this student.

    Notice where it has been typed in.
    This is where all command line arguments should be entered.
    These values remain the same for all runs,
    until they are changed in this same window.

  3. Then just click Apply, followed by Run.
    The screenshot below shows the output in the console window.


Another Example of a Java program using Command Line Arguments: Args.java

Another example is the Args class,
developed in the TestArgs Eclipse project.
This program requires more than one command line argument.

  1. Click on Run -> Run (not Run Last Launched).

  2. Click on the Arguments tab,
    in the large subwindow of the Run window.
    This action brings up the Program arguments window,
    where you should type in your input values.

    For the Args program,
    eight input argument values are needed.
    For this run, we have chosen eight random sets of
    characters, some numeric, some alphabetic, as input values:
    namely, 101, Joe, Larry, 93214, 3.145, 66, ABCDEF, xxxxx.
    Notice that there is at least one space between every two arguments.

  3. Then just click Apply, followed by Run.
    The screenshot below shows the output in the console window.

  4. If you were to click on Run -> Run Last Launched at this point,
    the same command line arguments would be used automatically,
    producing the same output.

  5. To change the value of the command line argument,
    you need to click on Run -> Run again,
    and change the argument(s) in the Program assignment window.


Further Example of a Java programs using Command Line Arguments: TempConversion.java

Yet another example is the TempConversionCL class,
developed in the TempConversion Eclipse project.
This program requires only one command line argument,
but this value must be converted from a String
to a double value to be used arithmetically.

  1. Again, click on Run -> Run (not Run Last Launched).

  2. Click on the Arguments tab,
    in the large subwindow of the Run window.
    This action brings up the Program arguments window,
    where you should type in your input values.

    For the TempConversionCL program,
    only one input argument value is needed:
    the value of the Celsius temperature.
    For this run, we have chosen 28.5 for
    this value of the Celsius temperature.

  3. Then just click Apply, followed by Run.
    The screenshot below shows the output in the console window.



Copyright © 2003: Colorado State University for Computer Science. All rights reserved.

Tuesday, February 23, 2010

Creating a JAR File

Sun Java
  • Java Developer Tools

    See and download all software tools available from Sun.

  • Java Standard Edition

    For developing and deploying Java applications for the desktop, servers, embedded, and real-time environments.

  • Java Enterprise Edition

    For enterprise, server-side Java applications.

  • Java Micro Edition

    For Java applications running on mobile devices.

  • Java Training

    Sharpen your Java skills with courses from the source.

  • Java Support

    Get dedicated help from Sun including technical assistance, product support, and support for deployed Java applications.


Solaris
  • OpenSolaris

    Download, develop and collaborate with OpenSolaris

  • Solaris

    Download the most advanced operating system in the world

  • Sun Studio

    Optimizing compilers and tools for C/C++/Fortran application development

  • Solaris Developer Center

    Explore the resources and community available to the Solaris developer.

  • Sun Developer Services

    Get technical assistance, product support, training, and other services from the source.

  • BigAdmin

    A community site with Solaris system administration information, hardware compatibility, a script library, and other resources for administrators of Sun products.

Communities
  • OpenJDK

    The place to collaborate on the open-source JDK, an implementation of the Java Platform, Standard Edition specification.

  • Mobile & Embedded

    The Mobile & Embedded Community enables and empowers developers to collaborate and innovate, driving the evolution and adoption of the Java(TM) Platform, Micro Edition (Java ME) for mobile and embedded devices.

  • GlassFish

    The GlassFish community is building free, open source, production-quality, enterprise software.

  • NetBeans

    You have the opportunity to submit bugs and feature requests in IssueZilla, submit news for the NetBeans Community, and contribute code or even create a project of your own. Welcome to the team!

  • OpenSolaris

    The OpenSolaris source code is already cutting edge, but innovation happens everywhere, so we welcome your involvement.

  • OpenSPARC

    OpenSPARC.net is the genesis of a vision to create a larger community where open conversations and collaborative development projects spawn dramatic innovations around chip design.

  • Open Storage

    The OpenSolaris storage community is your gateway to data management related communities and projects - file sharing, file systems, volume managers, data services, storage drivers, and much more.

  • OpenJFX

    Project OpenJFX is a community for sharing early versions of the JavaFX Script language and for collaborating on its development.

  • java.net

    A gathering place for Java technology enthusiasts and existing communities across industries, platforms, and interest groups.

  • Sun Student Developers

    The SDN Academic Developer Program offers you ready access to tools, resources, and student communities.

  • Java Community Process

    The JCP gives you a chance to both have your own work become an official component of the Java platform, and to offer suggestions for improving and growing the technology.


My SDN Account


Using JAR Files: The Basics

Creating a JAR File


Book Excerpt Index

The basic format of the command for creating a JAR file is:

jar cf jar-file input-file(s)

Let's look at the options and arguments used in this command:

  • The c option indicates that you want to create a JAR file.
  • The f option indicates that you want the output to go to a file rather than to stdout.
  • jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
  • The input-file(s) argument is a space-delimited list of one or more files that you want to be placed in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.

The c and f options can appear in either order, but there must not be any space between them.

This command will generate a compressed JAR file and place it in the current directory. The command will also generate a default manifest file for the JAR archive.

You can add any of these additional options to the cf options of the basic command:

Option Description
v Produces verbose output on stderr (in version 1.1) or stdout (in version 1.2) while the JAR file is being built. The verbose output tells you the name of each file as it's added to the JAR file.
0 (zero) Indicates that you don't want the JAR file to be compressed.
M Indicates that the default manifest file should not be produced.
m Used to include manifest information from an existing manifest file. The format for using this option is:
jar cmf existing-manifest jar-file input-file(s)
See Modifying a Manifest for more information about his option.
-C To change directories during execution of the command. Version 1.2 only. See below for an example.

In version 1.1, the JAR-file format supports only ASCII filenames. Version 1.2 adds support for UTF8-encoded names.

An Example

Let's look at an example. The JDK demos include a simple TicTacToe applet. This demo contains a bytecode class file, audio files, and images all housed in a directory called TicTacToe having this structure:

The audio and images subdirectories contain sound files and GIF images used by the applet.

To package this demo into a single JAR file named TicTacToe.jar, you would run this command from inside the TicTacToe directory:

jar cvf TicTacToe.jar TicTacToe.class audio images

The audio and images arguments represent directories, so the Jar tool will recursively place them and their contents in the JAR file. The generated JAR file TicTacToe.jar will be placed in the current directory. Because the command used the v option for verbose output, you'd see something similar to this output when you run the command:

adding: TicTacToe.class
(in=3825) (out=2222) (deflated 41%)
adding: audio/ (in=0) (out=0) (stored 0%)
adding: audio/beep.au
(in=4032) (out=3572) (deflated 11%)
adding: audio/ding.au
(in=2566) (out=2055) (deflated 19%)
adding: audio/return.au
(in=6558) (out=4401) (deflated 32%)
adding: audio/yahoo1.au
(in=7834) (out=6985) (deflated 10%)
adding: audio/yahoo2.au
(in=7463) (out=4607) (deflated 38%)
adding: images/ (in=0) (out=0) (stored 0%)
adding: images/cross.gif
(in=157) (out=160) (deflated -1%)
adding: images/not.gif
(in=158) (out=161) (deflated -1%)

You can see from this output that the JAR file TicTacToe.jar is compressed. The Jar tool compresses files by default. You can turn off the compression feature by using the 0 (zero) option, so that the command would look like:

jar cvf0 TicTacToe.jar TicTacToe.class audio images

You might want to avoid compression, for example, to increase the speed with which a JAR file could be loaded by a browser. Uncompressed JAR files can generally be loaded more quickly than compressed files because the need to decompress the files during loading is eliminated. However, there's a tradeoff in that download time over a network may be longer for larger, uncompressed files.

The Jar tool will accept arguments that use the wildcard * symbol. As long as there weren't any unwanted files in the TicTacToe directory, you could have used this alternative command to construct the JAR file:

jar cvf TicTacToe.jar *

Though the verbose output doesn't indicate it, the Jar tool automatically adds a manifest file to the JAR archive with pathname META-INF/MANIFEST.MF. See the Understanding the Manifest section for information about manifest files.

In the above example, the files in the archive retained their relative pathnames and directory structure. The Jar tool in version 1.2 of the Java Development Kit provides the -C option that you can use to create a JAR file in which the relative paths of the archived files are not preserved. It's modeled after GZIP's -C option.

As an example, suppose you wanted put audio files and gif images used by the TicTacToe demo into a JAR file, and that you wanted all the files to be on the top level, with no directory hierarchy. You could accomplish that by issuing this command from the parent directory of the images and audio directories:

jar cf ImageAudio.jar -C images * -C audio *

The -C images part of this command directs the Jar tool to go to the images directory, and the * following -C images directs the Jar tool to archive all the contents of that directory. The -C audio * part of the command then does the same with the audio directory. The resulting JAR file would have this table of contents:

META-INF/MANIFEST.MF
cross.gif
not.gif
beep.au
ding.au
return.au
yahoo1.au
yahoo2.au

By contrast, suppose that you used a command that didn't employ the -C option:

jar cf ImageAudio.jar images audio

The resulting JAR file would have this table of contents:

META-INF/MANIFEST.MF
images/cross.gif
images/not.gif
audio/beep.au
audio/ding.au
audio/return.au
audio/yahoo1.au
audio/yahoo2.au

Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.



Feedback

package

http://www.leepoint.net/notes-java/background/13files_and_directories/82packages-importing.html
Java Notes
Packages - Importing
Packages = directories. Multiple classes of larger programs are grouped together into a package. Packages correspond to directories in the file system, and may be nested just as directories are nested. Small, single-class, programs typically do not use packages, but a
Importing all classes from a package using *
Java libraries are organized in packages (directories). The most common way to get access to them is to use the import statement. For example,import java.util.*;
. . .
ArrayList studentNames; // ArrayList is a class in java.util
gives your program access to the all (that's what the "*" means) classes in the package java.util. The source files for these classes are in a directory named util, which is in a directory named java.
Importing each class explicitly
If you need only one class from a package, eg ArrayList, you can write import java.util.ArrayList;
. . .
ArrayList studentNames; // same as above.
You might think that importing all classes from a package is inefficient, but there is no noticeable difference in my experience. Consequently most programs use the ".*" style of import.
Using package qualifiers instead of imports
The import statement is not required. Class references can be made but explicit qualification with the "." operator. For example, java.util.ArrayList studentNames; // fully qualified. No need for import.
The fully qualified style is used in some textbooks, but is generally not used when programming, where the import style is almost universal.
However, there is one situation where qualification is necessary - when two classes have the same name, but are in different packages. For example, there is both java.util.Timer and java.swing.Timer. Because it's common to import all classes in both java.util and javax.swing, the name Timer is ambiguous and can't be used without qualification. import java.util.*; // The java.util package contains a Timer class.
import javax.swing.*; // The javax.swing package also contains a Timer class.
. . .
Timer t; // AMBIGUOUS - compilation error
java.util.Timer t; // OK, you've told the compiler which one you want.
Packages within packages require additional imports
The import statement gives access to classes in a package, but not to packages in that package. For example, import java.util.*;
does not give access to the classes of the package java.util.regex. To access classes in java.util and java.util.regex, import both. import java.util.*;
import java.util.regex.*;
Java's import is not the same as C++'s #include
C++'s #include is commonly used to for library headers, but the mechanism which is used is fundamentally different. #include inserts the entire source file that is referenced into your C++ program. In contrast, the Java import statement only looks up the the identifiers and their declarations from the compiled class file (not the source files).
Another difference is that Java imports are non-transitive. If class A imports packagex and packagex imports packagey, class A does NOT get access to packagey. In C++, the imports are transitive, which can lead to some unexpected effects.
A minor difference is that Java's import is a statement and requires a semicolon, unlike C++.
Copyleft 2006 Fred Swartz MIT License

Monday, February 22, 2010

string.split()

String sentence = "This is a sentence.";
String[] words = sentence.split(" ");

for (String word : words)
{
System.out.println(word);
}

Saturday, February 20, 2010

What will i get when i download Java Software?


What is Java technology and why do I need it?
This article applies to:
Platform(s): All Platforms
Java version(s): All JRE Versions
Java is a programming language and computing platform released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices.

Why do I need Java?
There are lots of applications and websites that won't work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

Is Java free to download?
Yes, Java is free to download. Get the latest version at http://java.com.

Why should I upgrade to the latest Java version?
The latest Java version contains important enhancements to improve performance, stability and security of the Java applications that run on your machine. Installing this free update will ensure that your Java applications continue to run safely and efficiently.
MORE TECHNICAL INFORMATION
Originally called OAK, it was renamed as the Java programming language in 1995.

What will I get when I download Java software?
The Java Runtime Environment (JRE) is what you get when you download Java software. The JRE consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform libraries. The JRE is the runtime portion of Java software, which is all you need to run it in your Web browser. When you download Java software, you only get what you need - no spyware, and no viruses.

What is Java Plug-in software?
The Java Plug-in software is a component of the Java Runtime Environment (JRE). The JRE allows applets written in the Java programming language to run inside various browsers. The Java Plug-in software is not a standalone program and cannot be installed separately.

I've heard the terms Java Virtual Machine and JVM. Is this Java software?
The Java Virtual Machine is only one aspect of Java software that is involved in web interaction. The Java Virtual Machine is built right into your Java software download, and helps the run Java applications.

math.hws.edu

Javanotes 5.1.1, Section 1.6 -- The Modern User Interface

Section 1.6

The Modern User Interface


http://math.hws.edu/javanotes/c1/s6.html

When computers were first introduced, ordinary people -- including most programmers -- couldn't get near them. They were locked up in rooms with white-coated attendants who would take your programs and data, feed them to the computer, and return the computer's response some time later. When timesharing -- where the computer switches its attention rapidly from one person to another -- was invented in the 1960s, it became possible for several people to interact directly with the computer at the same time. On a timesharing system, users sit at "terminals" where they type commands to the computer, and the computer types back its response. Early personal computers also used typed commands and responses, except that there was only one person involved at a time. This type of interaction between a user and a computer is called a command-line interface.

Today, of course, most people interact with computers in a completely different way. They use a Graphical User Interface, or GUI. The computer draws interface components on the screen. The components include things like windows, scroll bars, menus, buttons, and icons. Usually, a mouse is used to manipulate such components. Assuming that you have not just been teleported in from the 1970s, you are no doubt already familiar with the basics of graphical user interfaces!

A lot of GUI interface components have become fairly standard. That is, they have similar appearance and behavior on many different computer platforms including Macintosh, Windows, and Linux. Java programs, which are supposed to run on many different platforms without modification to the program, can use all the standard GUI components. They might vary a little in appearance from platform to platform, but their functionality should be identical on any computer on which the program runs.

Below is a very simple Java program -- actually an "applet," since it is running right here in the middle of a page -- that shows a few standard GUI interface components. There are four components that the user can interact with: a button, a checkbox, a text field, and a pop-up menu. These components are labeled. There are a few other components in the applet. The labels themselves are components (even though you can't interact with them). The right half of the applet is a text area component, which can display multiple lines of text, and a scrollbar component appears alongside the text area when the number of lines of text becomes larger than will fit in the text area. And in fact, in Java terminology, the whole applet is itself considered to be a "component." Try clicking on the button and on the checkbox, and try selecting an item from the pop-up menu. You will see a message in the text area about each action that you perform. You can type in the text field, but you might have to click on it first to activate it. When you press return while typing in the text field, you will see a message in the text area:

Java is not enabled in your browser,
but here is an image of the applet:

Now, Java actually has two complete sets of GUI components. One of these, the AWT or Abstract Windowing Toolkit, was available in the original version of Java. The other, which is known as Swing, is included in Java version 1.2 or later, and is used in preference to the AWT in most modern Java programs. The applet that is shown above uses components that are part of Swing. If your Web browser uses an old version of Java, you might get an error when the browser tries to load the applet. Remember that most of the applets in this textbook require Java 5.0 (or higher).

When a user interacts with the GUI components in this applet, an "event" is generated. For example, clicking a push button generates an event, and pressing return while typing in a text field generates an event. Each time an event is generated, a message is sent to the applet telling it that the event has occurred, and the applet responds according to its program. In fact, the program consists mainly of "event handlers" that tell the applet how to respond to various types of events. In this example, the applet has been programmed to respond to each event by displaying a message in the text area.

The use of the term "message" here is deliberate. Messages, as you saw in the previous section, are sent to objects. In fact, Java GUI components are implemented as objects. Java includes many predefined classes that represent various types of GUI components. Some of these classes are subclasses of others. Here is a diagram showing some of Swing's GUI classes and their relationships:

Don't worry about the details for now, but try to get some feel about how object-oriented programming and inheritance are used here. Note that all the GUI classes are subclasses, directly or indirectly, of a class called JComponent, which represents general properties that are shared by all Swing components. Two of the direct subclasses of JComponent themselves have subclasses. The classes JTextArea and JTextField, which have certain behaviors in common, are grouped together as subclasses of JTextComponent. Similarly JButton and JToggleButton are subclasses of JAbstractButton, which represents properties common to both buttons and checkboxes. (JComboBox, by the way, is the Swing class that represents pop-up menus.)

Just from this brief discussion, perhaps you can see how GUI programming can make effective use of object-oriented design. In fact, GUI's, with their "visible objects," are probably a major factor contributing to the popularity of OOP.

Programming with GUI components and events is one of the most interesting aspects of Java. However, we will spend several chapters on the basics before returning to this topic in Chapter 6.


Sunday, February 14, 2010

whitespace

http://www.java2s.com/Tutorial/Java/0040__Data-Type/isWhitespace.htm

isWhitespace():true if the argument is whitespace.

which is any one of the following characters:

space (' '), tab ('\t'), newline ('\n'), carriage return ('\r'),form feed ('\f')

public class MainClass {
public static void main(String[] args) {
char symbol = 'A';

if (Character.isWhitespace(symbol)) {
System.out.println("true");
}else{
System.out.println("false");
}
}
}

TextFileInput.java

http://dnixon.nyclocal.net/qc/cs212/proj-2-hints/TextFileInput.java.html

// TextFileInput.java // Copyright (c) 2000, 2005 Dorothy L. Nixon.  All rights reserved.  import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.IOException;  /**  * Simplified buffered character input  * stream from an input text file.  * Manages an input text file,  * handling all IOExceptions by generating  * RuntimeExcpetions (run-time error  * messages).  *  * If the text file cannot be created,  * a RuntimeException is thrown,  * which by default results an an  * error message being printed to  * the standard error stream.  *  * @author D. Nixon  */ public class TextFileInput  {     /**  Name of text file  */    private String filename;     /**  Buffered character stream from file  */    private BufferedReader br;       /**  Count of lines read so far.  */    private int lineCount = 0;     /**     * Creates a buffered character input     * strea, for the specified text file.     *     * @param filename the input text file.     * @exception RuntimeException if an     *          IOException is thrown when     *          attempting to open the file.     */    public TextFileInput(String filename)    {       this.filename = filename;       try  {          br = new BufferedReader(                   new InputStreamReader(                       new FileInputStream(filename)));       } catch ( IOException ioe )  {          throw new RuntimeException(ioe);       }  // catch    }  // constructor     /**     * Closes this character input stream.     * No more characters can be read from     * this TextFileInput once it is closed.     * @exception NullPointerException if     *        the file is already closed.     * @exception RuntimeException if an     *       IOException is thrown when     *       closing the file.     */    public void close()    {       try  {          br.close();          br = null;       } catch ( NullPointerException npe )  {          throw new NullPointerException(                         filename + "already closed.");       } catch ( IOException ioe )  {          throw new RuntimeException(ioe);       }  // catch    }  // method close     /**     * Reads a line of text from the file and     * positions cursor at 0 for the next line.     * Reads from the current cursor position     * to end of line.     * Implementation does not invoke read.     *     * @return the line of text, with     *         end-of-line marker deleted.     * @exception RuntimeException if an     *          IOException is thrown when     *          attempting to read from the file.     */    public String readLine()    {       return readLineOriginal();    }  // method readLine()     /**     * Returns a count of lines     * read from the file so far.     */    public int getLineCount()  { return lineCount; }     /**     * Tests whether the specified character is equal,     * ignoring case, to one of the specified options.     *     * @param toBeChecked the character to be tested.     * @param options a set of characters     * @return true if toBeChecked is     *         equal, ignoring case, to one of the     *         options, false otherwise.     */    public static boolean isOneOf(char toBeChecked,                                  char[] options)    {       boolean oneOf = false;       for ( int i = 0; i < oneof =" true;">toBeChecked     *         contains the same sequence of     *         characters, ignoring case, as one of the     *         options, false otherwise.     */    public static boolean isOneOf(String toBeChecked,                                  String[] options)    {       boolean oneOf = false;       for ( int i = 0; i < oneof =" true;" options ="="" length ="="" answer =" readLine();" answer ="="" optionstring =" options[0];" i =" 1;">true if the line matches     *        "Y", "yes", "1" "T", or "true".     *        false if the line matches     *        "N", "no", "0", "F", or "false".     * @exception RuntimeException if the line of text     *        does not match one of "Y", "N", "yes",     *        "no", "1", "0", "T", "F", "true", or "false",     *        or if an IOException is thrown when reading     *        from the file.     * @exception NullPointerException if the end of the     *        file has been reached.     */    public boolean readBooleanSelection()    {       String[] options = {"Y", "N", "yes", "no", "1", "0",                           "T", "F", "true", "false"};       String answer = readSelection(options);       return isOneOf(answer,                      new String[] {"Y", "yes", "1", "T", "true"} );    }  // method askUserYesNo     /**     * Reads a line of text from the file and     * increments line count.  (This method     * is called by public readLine and is     * final to facilitate avoidance of side     * effects when public readLine is overridden.)     *     * @return the line of text, with     *         end-of-line marker deleted.     * @exception RuntimeException if an     *          IOException is thrown when     *          attempting to read from the file.     */    protected final String readLineOriginal()    {        try  {           if ( br == null )              throw new RuntimeException(                                 "Cannot read from closed file "                                 + filename + ".");           String line = br.readLine();           if ( line != null )              lineCount++;           return line;        } catch (IOException ioe)  {           throw new RuntimeException(ioe);        }  // catch    }  // method readLineOriginal }  // class TextFileInput

Wednesday, February 10, 2010

Exceptions

Lesson: Exceptions
The Java programming language uses exceptions to handle errors and other exceptional events. This lesson describes when and how to use exceptions.

What Is an Exception?

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

The Catch or Specify Requirement

This section covers how to catch and handle exceptions. The discussion includes the try, catch, and finally blocks, as well as chained exceptions and logging.

How to Throw Exceptions

This section covers the throw statement and the Throwable class and its subclasses.

Unchecked Exceptions — The Controversy

This section explains the correct and incorrect use of the unchecked exceptions indicated by subclasses ofRuntimeException.

Advantages of Exceptions

The use of exceptions to manage errors has some advantages over traditional error-management techniques. You'll learn more in this section.

Summary

Questions and Exercises


We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies — your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.

Echo 1 Items
Admin
Dee
its great can i be updated through ma e-mail all the time
Thursday, May 28, 2009, 07:31:28
FlagLikeReply
Liked by
Guest

Using Swing Components

Lesson: Using Swing Components
Examples Index

This lesson gives you the background information you need to use the Swing components, and then describes every Swing component. It assumes that you have successfully compiled and run a program that uses Swing components, and that you are familiar with basic Swing concepts. These prerequisites are covered in Getting Started with Swing and Learning Swing with the NetBeans IDE.

A Visual Index to the Swing Components (Java Look and Feel)
A Visual Index to the Swing Components (Windows Look and Feel)

Before you get started, you may want to check out these pages (from the Graphical User Interfaces lesson in the Core trail) which have pictures of all the standard Swing components, from top-level containers to scroll panes to buttons. To find the section that discusses a particular component, just click the component's picture.

Using Top-Level Containers

Discusses how to use the features shared by the JFrame, JDialog, and JApplet classes — content panes, menu bars, and root panes. It also discusses the containment hierarchy, which refers to the tree of components contained by a top-level container.

The JComponent Class

Tells you about the features JComponent provides to its subclasses — which include almost all Swing components — and gives tips on how to take advantage of these features. This section ends with API tables describing the commonly used API defined by JComponent and its superclasses,Container and Component.

Using Text Components

Describes the features and API shared by all components that descend from JTextComponent. You probably do not need to read this section if you are just using text fields (formatted or not) or text areas.

How to...

Sections on how to use each Swing component, in alphabetical order. We do not expect you to read these sections in order. Instead, we recommend reading the relevant "How to" sections once you are ready to start using Swing components in your own programs. For example, if your program needs a frame, a label, a button, and a color chooser, you should read How to Make Frames, How to Use Labels, How to Use Buttons, and How to Use Color Choosers.

Using HTML in Swing Components

Describes how to vary the font, color, or other formatting of text displayed by Swing components by using HTML tags.

Using Models

Tells you about the Swing model architecture. This variation on Model-View-Controller (MVC) means that you can, if you wish, specify how the data and state of a Swing component are stored and retrieved. The benefits are the ability to share data and state between components, and to greatly improve the performance of components such as tables that display large amounts of data.

Using Borders

Borders are very handy for drawing lines, titles, and empty space around the edges of components. (You might have noticed that the examples in this trail use a lot of borders.) This section tells you how to add a border to any JComponent.

Using Icons

Many Swing components can display icons. Usually, icons are implemented as instances of the ImageIcon class.

Solving Common Component Problems

This section discusses solutions to common component-related problems.

Questions and Exercises

Try these questions and exercises to test what you have learned in this lesson.

We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies — your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.

Echo 6 Items
Admin
lester
hi
Sunday, August 02, 2009, 03:43:10
FlagLikeReply
Guest
hello,
im tring to find a code for a simple date chooser.
i need to get dates from my users that will be formatted like this- dd/mm/yyyy

thank u
Monday, August 24, 2009, 19:01:30
FlagLikeReply
Prasant
This is very helpful site for learning latest java programming.
im very thankful to sun.
Saturday, October 03, 2009, 16:08:23
FlagLikeReply
KingNiNe
Hi~
Monday, November 16, 2009, 03:09:02
FlagLikeReply
Tirunelveli
fine la...
Monday, December 21, 2009, 07:46:30
FlagLikeReply
Rakesh Singh
it's excellent for beginners to learn JAVA.
Iwould like to recomment that there should be downloading facility too.
Wednesday, January 13, 2010, 10:25:22
FlagLikeReply