Eclipse Tutorial
Eclipse Tutorial
2. 3. 4. 5.
5.1 General Usages (for all Programming Tasks) 5.2 Updating Eclipse 5.3 For Java Application Development Only
Writing your First Java Program in Eclipse Read the Documentation Debugging Programs in Eclipse Tips & Tricks
6. 7. 8. 9.
File I/O in Eclipse Writing Swing Applications using Eclipse GUI Builder Eclipse for C/C++ Programming Eclipse PDT (PHP Developer Tool)
9.1 Installing Eclipse PDT 9.2 Writing a Hello-world PHP program in Eclipse PDT 9.3 Debugging PHP Script in Eclipse PDT
10. Eclipse and Database Development (MySQL) 11. Developing and Deploying Web Applications in Eclipse for Java EE
11.1 11.2 11.3 11.4 11.5 11.6 Setting Up Eclipse for Web Development Writing a Hello-world JSP Page Writing a Hello-world Servlet Exporting a Web Application as a WAR file Writing a Hello-world JSF Page Debugging Web Applications
Eclipse Versions
The various versions are:
Eclipse 1.0 (November 7, 2001): based on an earlier Java IDE called VisualAge from IBM.
Eclipse 2.0 (June 28, 2002) Eclipse 2.1 (March 28, 2003) Eclipse 3.0 (June 25, 2004) Eclipse 3.1 (June 28, 2005) Eclipse 3.2 (June 30, 2006) (Callisto - named after one of the Jupiter's Galilean moons): started annual simultaneous release of all the related Eclipse projects. Eclipse 3.3 (June 25, 2007) (Europa - named after another Jupiter's Galilean moons) Eclipse 3.4 (June 19, 2008) (Ganymede - named after yet another Jupiter's Galilean moons) Eclipse 3.5 (June 12, 2009) (Galileo - named after the great 17th century scientist and astronomer Galileo Galilei) Eclipse 3.6 (June 23, 2010) (Helios - named after god of the sun in Greek Mythology) Eclipse 3.7 (June 23, 2011) (Indigo) Eclipse 4.2 (June 27, 2012) (Juno)
Step 1: Download
Download Eclipse from http://www.eclipse.org/downloads. For beginners, choose the minimal Eclipse IDE for "Java" Developers (e.g., "eclipse-java-juno-win32.zip").
Step 2: Unzip
To install Eclipse, simply unzip the downloaded file into a directory of your choice (e.g., "d:\myproject"). There is no need to run any installer. Moreover, you can simply delete the entire Eclipse directory when it is no longer needed (without running any un-installer). You are free to move or rename the directory. You can install (unzip) multiple copies of Eclipse in the same machine.
Step 2: Write a Hello-world Java Program 1. In the "Package Explorer" (left panel) Right-click on "FirstProject" (or use the
"File" menu) New Class. 2. The "New Java Class" dialog pops up.
a. In "Name" field, enter "Hello". b. Check "public static void main(String[] args)" box.
c. Click "Finish".
2.
3. 4. 5. 6.
The source file "Hello.java" opens on the editor panel. Enter the following codes:
public class Hello { // "Hello.java" public static void main(String[] args) { System.out.println("Hello, world!"); } }
3.
NOTES:
You should create a new Java project for each of your Java application. Nonetheless, Eclipse allows you to keep more than one programs in a project, which is handy for writing toy programs (such as your tutorial exercises). If you have more than one files withmain() method in one project, you need to right-click the source and choose "Run As" "Java Application" to run that particular source. Clicking the "Run" button runs the recently-run program (based on the previous configuration). Try clicking on the "down-arrow" besides the "Run" button.
A breakpoint suspends program execution for you to examine the internal states (e.g., value of variables) of the program. Before starting the debugger, you need to set at least one breakpoint to suspend the execution inside the program. Set a breakpoint atmain() method by double-clicking on the left-margin of the line containing main(). Ablue circle appears in the left-margin indicating a breakpoint is set at that line.
Right click anywhere on the source code (or from the "Run" menu) "Debug As" "Java Application" choose "Yes" to switch into "Debug" perspective (A perspective is a particular arrangement of panels to suits a certain development task such as editing or debugging). The program begins execution but suspends its operation at the breakpoint, i.e., the main() method. As illustrated in the following diagram, the highlighted line (also pointed to by a blue arrow) indicates the statement to be executed in the next step.
Click the "Step Over" button (or select "Step Over" from "Run" menu) to single-step thru your program. At each of the step, examine the value of the variables (in the "Variable" panel) and the outputs produced by your program (in the "Console" Panel), if any. You can also place your cursor at any variable to inspect the content of the variable. Single-stepping thru the program and watching the values of internal variables and the outputs produced is the ultimate mean in debugging programs - because it is exactly how the computer runs your program!
Click the "Java" perspective icon on the upper-right corner to switch back to the "Java" perspective for further programming (or "Window" menu Open Perspective Java). Important: I can's stress more that mastering the use of debugger is crucial in programming. Explore the features provided by the debuggers.
1.
2.
"Key" choose "Command", "Content Assist". (Alternatively, in "Window" "Preferences" type "key" as filter text and choose "General" "Key".) 3. Intelli-Sense (ctrl-space): You can use ctrl-space to activate the "intellisense" (or content assist). That is, Eclipse will offer you the choices, while you are typing.
4.
5. 6.
could click on the "light bulb" to display the error message, and also select from the available hints for correcting that syntax error. 7. Refactor (or Rename) (alt-shift-r): You can rename a variable, method, class, package or even the project easily in Eclipse. Select and right-click on the entity to be renamed "Refactor" "Rename". Eclipse can rename all the occurrences of the entity. 8. Line Numbers: To show the line numbers, choose "Window" menu "Preferences" "General" "Editors" "Text Editors" Check the "Show Line Numbers" Box. You can also configure many editor options, such as the number of spaces for tab. Alternatively, you can right-click on the left-margin, and check "Show Line Numbers".
9.
10. Changing Font Type and Size: From "Window" menu "Preferences" "General" "Appearance" "Colors and Fonts" expand "Java" "Java Editor Text Font" "Edit". (Alternatively, in "Window" "Preferences" type "font" as filter text and choose the appropriate entry.) 11. Unicode Support: To enable Unicode support, select "Window" menu Preferences General Workspace Text file encoding UTF-8. This sets the default character set used for file encoding, similar to VM's command-line option Dfile.encoding=UTF-8. Commonly used charsets for Unicode are UTF-8, UTF-16 (with BOM), UTF-16BE, UTF-16LE. Other charsets are US-ASCII, ISO-8859-1. 12. Mouse Hover-over: In debug mode, you could configure to show the variable's value when the mouse hovers over the variable. Select "Window" menu "Preferences" "Java" "Editor" "Hover". 13. Comparing Two Files: In "Package Explorer", select two files (hold the control key) Right-click Compare with. 14. Useful Eclipse Shortcut Keys:
o o o o o
F3: Goto the declaration of the highlighted variable/method. Ctrl-Shift-G: Search for ALL references of the highlighted variable/method in workspace. Ctrl-G: Search for the Declaration of a variable/method in workspace. Don't use Find (Ctrl-F), but use the above context-sensitive search. Ctrl-Shift-F: Format the source code. Ctrl-Shift-O: Organize imports.
o o
15. Package Explorer vs. Naviagator: We usually use "Package Explorer" in programming, but it will not show you all the folders and files under the project. On the other hand, "Navigator" is a file manager that shows the exact file structure of the project (similar to Windows Explorer). You can enable the Navigator by "Window" Show view Navigator.
16. Let me know if you have more tips to be included here.
2.
Small
Toy
Java
Programs: You
can
keep
many
small
programs
(with main()) in one Java project instead of create a new project for each toy program. To run the desired program, right-click on the source file "Run as" "Java Application".
3.
Scanner/printf() and
JDK
1.5: If
you
encounter
syntax
error
in
using printf() or Scanner (which are available from JDK 1.5), you need to check your compiler settings. Select "Window" menu Preferences open the "Java" node select "Compiler" in "Compiler compliance level" select the latest release, which should be "1.5" or above. 4. Command-Line Arguments: To provide command-line arguments to your Java program in Eclipse, right-click on the source file "Run Configurations" Under the "Main" panel, check that "Project" name and "Main Class" are appropriate Select the "Argument" tab type your command-line arguments inside the "Program Arguments" box "Run".
5.
Resolving
Import
(Ctrl-Shift-o) :
To
ask
Eclipse
to
insert
the import statements for classes. Useful when you copy a large chunk of codes without the corresponding import statements. 6. Including Another Project: To include another project in the same work space, right-click on the project Build Path Configure Build Path... Select "Projects" tab "Add..." to select project in the existing work space OK. 7. Exporting a Project to a JAR file: Right-click on the project Export... Java, JAR File Next Select the files to be exported Next Next In "JAR
Manifest Specification" dialog, enter the main class (if you wish to run the JAR file directly) Finish. 8. Unit Testing: If you keep your test in another project, you need to include the project under test in your Build Path (see above). To create a test case: Right-click on the project New JUnit Test Case the "New JUnit Test Case" dialog appears. Select "New JUnit 4 Test". In "Name", enter your class name. In "Class under test", browse and select the class to be tested. To run the test: Right-click "Run As" "JUnit Test". The results are displayed in a special "JUnit console".
9.
Adding External JAR files & Native Libraries (".dll", ".lib", ".a", ".so"): Many external Java packages (such as JOGL, Java3D, JAMA, etc) are
available to extend the functions of JDK. These packages typically provide a " lib" directory containing JAR files (".jar") (Java Archive - a single-file package of Java classes) and native libraries (".dll", ".lib" for windows, ".a", ".so" for Lunix and Mac). To include these external packages into an Eclipse's project, right-click on the project Build Path Add External Archives Navigate to select the JAR files (".jar") to be included. In "Package Explorer", right-click on the JAR file added Properties: o To include native libraries (".dll", ".lib", ".a", ".so"), select "Native Library"
o o
"Location Path" "External Folder". To include the javadoc, select "JavaDoc Location" "JavaDoc URL" You can specify a local file or a remote link. To include source file (for debugging), select "Java Source Attachment".
All the above options are also accessible via project's property "Build Path". Notes: The JAR files must be included in the CLASSPATH. The native library directories must be included in JRE's property " java.library.path", which normally but not necessarily includes all the paths from the PATH environment variable. Read "External JAR files and Native Libraries". 10. Creating a User Library: You can also create a Eclipse's user library to include a set of JAR files and native libraries, that can then be added into subsequent Eclipse projects. For example, I created a user library for "JOGL" as follows: a. From "Window" menu Preferences Java Build Path User Libraries New In "User library name", enter "jogl". The "User Library" dialog appears. b. In "User Library" dialog Select "jogl" Add JAR... Navigate to <JOGL_HOME>/lib, and select "gluegen-rt.jar" and "jogl.jar". c. Expand the "jogl.jar" node Select "Native library location: (none)" Edit... External Folder... select <JOGL_HOME>/lib.
Javadoc in archive In "Archive Path", "Browse" and select the downloaded JOGL API documentation zip-file In "Path within archive", "Browse" and expand the zip-file to select the top-level path (if any) Validate. Alternatively, you can provide the path to the un-zipped javadocs. This is needed for Eclipse to display javadoc information about classes, fields, and methods.
e. You may provide the source files by editing "Source attachment: (none)".
Source is needed only if you are interested to debug into the JOGL source codes. For EACH subsequent Java project created that uses JOGL, right-click on the project Build Path Add Libraries Select "User Library" Check "jogl". 2. Running an External Program: Suppose that you want to run a Perl script on the selected file, you can configure an external tool as follows:
a. From "Run" menu External Tools External Tools Configuration... The
perl interpreter "perl" In "Arguments", enter "path/scriptname.pl $ {resource_loc}", where${resource_loc} is an Eclipse variable that denotes the currently selected resource with absolute path.
d. Choose the "Common" tab In "Standard Input and Output", uncheck
"Allocate Console", check "File" and provide an output file (e.g., d:\temp\$ {resource_name}.txt).
e. (If you use the CYGWIN perl interpreter, need to set environment variable
CYGWIN=nodosfilewarning to disable warning message.) To run the configured external tool, select a file run external tool tool name. 2. Viewing Hex Code of Primitive Variables in Debug mode: In debug perspective, "Variable" panel Select the "menu" (inverted triangle) Java Java Preferences... Primitive Display Options Check "Display hexadecimal values (byte, short, char, int, long)". 3. Adding a New Version of JDK/JRE: First, you can check the installed JDK/JRE via "Window" menu "Preferences" Expand "Java" node "Installed JREs". Check the "Location" current JRE installed to make sure that it is the intended one. You can use the "Add" button to add a new version of JRE. For program development, I recommend that you add the JDK (instead of JRE). [The "Location" decides the extension directory used for including additional JAR files, e.g., $JAVA_HOME\jre\lib\ext.]
6.
Suppose that your want to write a Java program, which inputs from a text file called "xxxx.in" and outputs to a text file called " xxxx.out". This is a little tricky under Eclipse due to: 1. When you create a text file in Windows' Notepad and saved it as " xxxx.in", Notepad will append the ".txt" to your file and it becomes " xxxx.in.txt". Worse still, the Windows' Explorer, by default, will not show the " .txt" extension. (The first thing I always do to an alien computer is to change this setting. From "Tools" menu Folder Options... View Uncheck "Hide extensions for known file types".) You need to put a pair of double quotes around xxxx.in to override the default ".txt" extension. This is one good reason not to use Notepad for programming at all. You should use Eclipse to create the text file instead. 2. Which directory to keep the input file "xxxx.in" in Eclipse?
o
If you did not separate the sources and class files into two separate directories, then the answer is straight forward, because there is only one directory to place your input file.
If you choose to keep your sources and class files in two separate directories, eclipse will create two sub-directories "src" and "bin" under the base directory. BUT you need to put your input file " xxxx.in" in the base directory of your project, instead of the "src" or "bin"..
Put the sources, class files, and the input/output files in the same directory. (When you create a new project, select "Use project folder as root for sources and class files" in "Project Layout".) (But put your sources and class files in separate directories for big project.)
You can create you input file from eclipse directly via "File" menu "New" "File". Remember to add a newline to the end of your input file. You may need to right-click the project and select "Refresh" to see the output file "xxxx.out" created in the package explorer. To open the "xxxx.in" and "xxxx.out": right-click Open With Text Editor.
public class FileIOTest { // saved as "FileIOTest.java" public static void main (String [] args) throws IOException { Scanner in = new Scanner(new File("FileIOTest.in")); // file input Formatter out = new Formatter(new File("FileIOTest.out")); // file output int a = in.nextInt(); int b = in.nextInt(); out.format("%d\n",a+b); // format() has the same syntax as printf() out.close(); } } // flush the output and close the output file
Create the input text file called "FileIOTest.in" with the following contents and terminated with a newline:
55 66
4.
In "Layouts", select "FlowLayout" and click on the "design form". From "Components", select "JLabel" and click on the desing form. Change the label text to "Counter: ". Select a "JTextField" and place it on the design form. Change the text to "0". Select a "JButton" and place it on the design form. Change
5.
the text label to "Count". 6. To attach a event-handler to the button, double-click the JButton to switch into the "Source" pane, with the the actionPerformed() as follows:
7. 8. 9. }
event-handler
skeleton
created.
Complet
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59}
FirstSwingProgram frame = new FirstSwingProgram(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public FirstSwingProgram() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5)); JLabel lblNewLabel = new JLabel("Counter: "); contentPane.add(lblNewLabel); textField = new JTextField(); textField.setText("0"); contentPane.add(textField); textField.setColumns(10); JButton btnCount = new JButton("Count"); btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { count++; textField.setText(count + ""); } }); contentPane.add(btnCount); }
(@ http://www.netbeans.org),
PHPEclipse
b. The "Install" dialog appears. In "Work with" "http://download.eclipse.org/releases/juno" (for Eclipse "http://download.eclipse.org/releases/helios/" (for Eclipse 3.7).
field, 4.2)
enter or
c. In "Name" box, expand "Programming Language" node Check "PHP Development Tools (PDT) SDK Features" "Next" ... "Finish". 2. You need to configuring Eclipse to support PHP development. Launch Elcipse Select menu "Window" "Preferences" Expand "PHP" node: a. Select "PHP Servers" Check that there is an entry with "Name" of "Default PHP Server" and "URL" "http://localhost".
b. Select "PHP Executable" "Add" In "Name", Enter a name, e.g. "WampServer". In "Executable Path", enter the location of PHP executable "php.exe". For WampServer, it shall be "<WAMPSERVER_HOME>\bin\php\php5.x.x\php.exe". In "PHP ini file", enter the php configuration file used by the WampServer, e.g., "<WAMPSERVER_HOME>\bin\apache\Apache2.2.xx\bin\php.ini". In "PHP Debugger", select "XDebug", which is bundled in WampServer.
c. Select "Debug" In "PHP Debugger", select "XDebug". In "Server", select "Default PHP Server". In "PHP Executable", select the PHP Executable configured in the previous step, i.e., "WampServer". d. Select "PHP Manual" Check that there is an entry with "Site Name" of "php.net" with "URL" of "http://www.php.net/manual/en". e. Browse through other settings for PHP.
location", enter your web server's root directory followed by the project name, e.g., d:\WampServer\www\hello. "Finish".
3.
4. 5.
Write your PHP program: Right-click on the project "hello" "New" "PHP File". Enter the following codes and saved as "HelloObj.php":
<?php class Hello{ // Variables var $message; // Constructor function __construct(){ $this->message= "Hello World!"; } /** * Function that prints the value of the instance variable $message */ function printMessage(){ echo $this->message; }
6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. } ?>
Again, create a new PHP file for the following driver program "HelloDriver.php":
<?php include_once('HelloObj.php'); $hello= new hello(); $hello->printMessage(); ?>
21. To run the program, right-click anywhere on " HelloDriver.php" "Run As" "PHP Script" (output shown in console) or "PHP Web Page" (output shown in Eclipse internal browser or external browser).
To create a new SQL script, choose File New SQL File You may use an existing project or create a new project (General - Project or Web - Dynamic Web Project) Enter filename, and set the connection profile name Finish. Enter a SQL statement (e.g., SELECT * FROM tablename) Right-click on the text "Execute Current Text" or "Execute All".
3.
To use an existing SQL file, drop the file into a project and open the SQL file. In Connection profile, set the type and connection name. Right-click on a statement "Execute ...".
4.
To CURD (create-update-read-delete) tables, in "Datasource Explorer" (of the "Database Development" perspective), expand "database" to view the tables. Right-right on the table Datat Edit.
3.
Configuring Web Server: Launch Eclipse Window Preferences Expand the "Server" node "Runtime Environments" "Add..." Expand "Apache" and select "Apache Tomcat v7.0" Enter the "Tomcat Installation Directory" "Finish".
9. 1.
To execute the JSP, right-click on "Hello.jsp" Run As Run on Server. Create a new Web Application: File New Dynamic Web Project (under "Web"
14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24.
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set the response message MIME type (in Content-Type response header) response.setContentType("text/html"); // Get an output Writer to write the response message over the network PrintWriter out = response.getWriter(); // Write the response message (in an HTML page) to display "Hello, world!" out.println("<!DOCTYPE html>"); out.println("<html><head>"); out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF8'>"); 25. out.println("<title>Hello Servlet</title></head>"); 26. out.println("<body><h1>Hello, World!</h1>"); 27. out.println("<p>Your IP address is " + request.getRemoteAddr() + "</p>"); 28. out.println("<p>Your user agent is " + request.getHeader("user-agent") + "</p>"); 29. out.println("</body></html>"); 30. } }
(For Servlet 2.4/2.5 with Tomcat 6) The annotation @WebServlet is new in Servlet 3.0 and is not supported in Servlet 2.4/2.5. Hence, you need to manually configure the URL for the servlet in the Web Application Deployment Descriptor "web.xml" under directory "WEB-INF", as follows:
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true">
31. To execute the Servlet, right-click on the " HelloServlet" project "Run As" "Run on Server" Change the URL to "http://localhost:8080/HelloServlet/sayhello".
1.
To deploy the war file in Tomcat, simply drop the war file into Tomcat's "webapps" folder. The war file will be automatically extracted and deployed. The web application name is the war-filename.
2.
You could use WinZip (or WinRAR) to view the content of the war file, as war-file is in ZIP format.