Saturday, April 4, 2020

mazing Eclipse IDE Shortcuts every Java Developer should know








Examples from Java Network Programming, 4th Edition

Local copies from http://www.cafeaulait.org/books/jnp4/examples/ for quick reference

Thursday, April 2, 2020

[Solved] Source Folder Is Not A Java Project Error In Eclipse

https://javahungry.blogspot.com/2014/02/best-books-for-learning-java-must-read.html



If you are trying to import maven project into eclipse or creating a maven web project in eclipse, it might be possible that you face following error : Source folder is not a Java project. There are two ways to solve this error. One is using mvn eclipse:eclipse (deprecated) and other is by converting project into faceted form.

Read Also :   Java Was Started by Returned Exit Code=13 Error in Eclipse

Understand the error

This error occurs when the project created by you is not a java project in eclipse. If you try to add new java class to such project then "Source folder is not a Java Project error" occurs.


Producing error : Source folder is not a Java Project

[Fixed] Error : Source folder is not a Java Project

1. Right click on your project and select "Properties"

2. In Properties, click on "Project Facets"

3. Then click on "Convert to faceted form..."

Steps to solve error : Source folder is not a Java Project

4. Then select "Java"

solve error : Source folder is not a Java Project


5. Click on "Apply and Ok"

Yayy!! This will resolve the error "Source folder is not a Java Project". Please mention in the comments if you have any questions.

Eclipse for Java How To Install Eclipse and Get Started with Java Programming (on Windows, macOS and Ubuntu)

https://www.ntu.edu.sg/home/ehchua/programming/howto/EclipseJava_HowTo.html

.  How to Install Eclipse IDE 2019-12 for Java Developers

1.1  How to Install Eclipse on Windows

Step 0: Install JDK
To use Eclipse for Java programming, you need to first install Java Development Kit (JDK). Read "How to Install JDK for Windows".
Step 1: Download
Download Eclipse from https://www.eclipse.org/downloads. Under "Get Eclipse IDE 2019-12" ⇒ Click "Download Packages". For beginners, choose the "Eclipse IDE for Java Developers" and "Windows 64-bit" (e.g., "eclipse-java-2019-12-R-win32-x86_64.zip" - about 201MB) ⇒ Download.
Step 2: Unzip
To install Eclipse, simply unzip the downloaded file into a directory of your choice (e.g., "c:\myProject").
I prefer the zip version, because 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.


1.3  How to Install Eclipse on Ubuntu Linux

Eclipse comes with many flavors (See "Eclipse Packages" @ https://www.eclipse.org/downloads/compare.php):
  • To use Eclipse for Java programming, choose "Eclipse IDE for Java Developers" (JavaSE) or "Eclipse IDE for Java EE Developers" (JavaEE). You need to first install JDK. Read "How to install JDK on Ubuntu".
  • To use Eclipse for PHP programming, choose "Eclipse IDE for PHP Developers".
  • To use Eclipse for C/C++ programming, choose "Eclipse IDE for C/C++ Developers".
Nonetheless, you can install any package, and then add more features when needed.
To install Eclipse (e.g, for Java Programming):
  1. Download Eclipse from http://www.eclipse.org/downloads/. Under "Get Eclipse IDE 2019-12" ⇒ Click "Download Packages". Choose "Eclipse IDE for Java Developers" for Java SE program development; or "Eclipse IDE for Java EE Developers" for developing webapps ⇒ Linux 64-bit. You will receive a tarball (e.g., "eclipse-java-2019-12-R-linux-gtk-x86_64.tar.gz") in the "~/Downloads" folder.
  2. We shall install Eclipse under /usr/local.
    // Unzip the tarball into /usr/local
    $ cd /usr/local
    $ sudo tar xzvf ~/Downloads/eclipse-java-2019-12-R-linux-gtk-x86_64.tar.gz
          // Extract the downloaded package
          // x: extract, z: for unzipping gz, v: verbose, f: filename
          // Extract into /usr/local/eclipse
          // You can also unzip in "File Explorer" by double-clicking the tarball.
     
    // (Optional) Change ownership
    $ cd /usr/local
    $ sudo chown -R your-username:your-groupname eclipse
          // Change ownership to your chosen username and groupname
          // -R recursive
     
    // Set up a symlink to /usr/bin (which is in the PATH)
    $ cd /usr/bin
    $ sudo ln -s /usr/local/eclipse/eclipse
          // Make a symlink in /usr/bin, which is in the PATH.
    $ ls -ld /usr/bin/eclipse
    lrwxrwxrwx 1 root root 26 Aug 30 11:53 /usr/bin/eclipse -> /usr/local/eclipse/eclipse
    $ which eclipse
    /usr/bin/eclipse
To run Eclipse, open the "/usr/local/eclipse" folder and click on the "Eclipse" icon; or start a "Terminal", enter "eclipse".
Lock Eclipse on Launcher
Simply start Eclipse. Right-click the Eclipse icon ⇒ Lock to Launcher.
(For older version - If the above don't work) Create a /usr/share/applications/eclipse.desktop file with the following contents:
[Desktop Entry]
Name=Eclipse 
Type=Application
Exec=eclipse
Terminal=false
Icon=/usr/local/eclipse/icon.xpm
Comment=Integrated Development Environment
NoDisplay=false
Categories=Development;IDE;
Name[en]=Eclipse
Start Eclipse, right-click on the Eclipse icon on launcher ⇒ lock to launcher.

5.  Tips & Tricks

5.1  General Usages (for all Programming Tasks)

These are the features that I find to be most useful in Eclipse:
  1. Maximizing Window (Double-Clicking): You can double-click on the "header" of any panel to maximize that particular panel, and double-click again to restore it back. This feature is particularly useful for writing source code in full panel.
  2. Shorthand Templates (sysout, for,...): You can type "sysout" followed by a ctrl+space (or alt-/) as a shorthand for typing "System.out.println()".
    The default shortcut key (ctrl-space or alt-/) depends on the system. Check your system's shortcut key setting in "Edit" ⇒ "Content Assist" ⇒ "Default". Take note that many of you use ctrl+space to switch between input languages. You need to reconfigure either your language switching hot-key or Eclipse.
    Similarly, you can type "for" followed by ctrl-space (or alt-/) to get a for-loop.
    You can create your own shorthand in "Window" menu ⇒ "Preferences" ⇒ "Java" ⇒ "Editor" ⇒ "Templates". (Alternatively, in "Window" ⇒ "Preferences" ⇒ type "template" as filter text and choose "Java" ⇒ "Editor" ⇒ "Templates".)
    You can change your key settings in "Window" menu ⇒ "Preferences" ⇒ "General" ⇒ "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 "intelli-sense" (or content assist). That is, Eclipse will offer you the choices, while you are typing.
  4. Source Formatting (ctrl-shift-f): Right-click on the source. Choose "Source" ⇒ "Format" to let Eclipse to layout your source codes with the proper indentation.
  5. Source Toggle Comment (ctrl-/): To comment/uncomment a block of codes, choose "Source" ⇒ "Toggle Comment".
  6. Hints for Correcting Syntax Error: If there is a syntax error on a statement, a red mark will show up on the left-margin on that statement. You 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. Error Message Hyperlink: Click on an error message will hyperlink to the corresponding source statement.
  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:
    • 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.
    • Alt-Shift-R: Rename. (Don't use Find/Replace.)
    • Ctrl-Space: auto-complete.
  15. Package Explorer vs. Navigator: 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. Spell Check: To enable spell check, select Window ⇒ Preferences ⇒ type "spell" in the filter ⇒ General ⇒ Editors ⇒ Text Editors ⇒ Spelling ⇒ Check "Enable spell checking". Also provide a "User defined dictionary" (with an initially empty text file).
    To correct mis-spell words, right-click and press ctrl-1 (or Edit menu ⇒ Quick Fix).
  17. Eclipse's Log File: Goto Help ⇒ about Eclipse ⇒ Installation details ⇒ Configuration ⇒ View Error Log.
  18. Viewing two files in split screen: Simply click and hold on the title of one file and drag it to the lower side of the screen. [To view the same file on split screen, create a new editor window by selecting Window ⇒ New Editor; and drag one window to the lower side of the screen.]
  19. Block Select (Column Select): Push Alt-Shift-A to toggle between block-select mode and normal mode.
  20. Snippets:
    • To view the snippet window: choose "Window" ⇒ Show View ⇒ Snippets.
    • To create a new snippet category: Right-click ⇒ Customize ⇒ New.
    • To create a new snippet item: Copy the desired text ⇒ Select the snippet category ⇒ paste as snippet.
    • To insert a snippet: place the cursor on the desired location at the editor panel ⇒ click the snippet item.
  21. Word Wrap (Line Wrap): Word-wrap (or line-wrap) is essential for editing long HTML documents without the horizontal scroll bar. However, the Eclipse's HTML Editor and Text Editor do not support word-wrap.
    You could install a plug-in called "Word Wrap" from http://ahtik.com/eclipse-update/.
    Choose "Help" ⇒ Install New Software ⇒ in "Work with" Enter "http://ahtik.com/eclipse-update/".
    To activate word wrap, right-click on the editor panel ⇒ select "Word Wrap".
  22. Creating "link folder" in project: You do not have to place all the folders under the project base directory, instead, you can use so-called "link folders" to link to folder outside the project base directory.
    To create a link folder in a project, right-click on the project ⇒ File ⇒ New ⇒ Folder ⇒ Advanced ⇒ Check Link to alternate Location (Linked Folder).
  23. Running Eclipse in "clean" mode: You can run eclipse in so-called "clean" mode, which wipes all the cached data and re-initialize the cache, by running eclipse from command-line with "-clean" argument (i.e., "eclipse -clean"). It is useful if something is not working proper, especially if you install a new copy of Eclipse.
  24. Show the Right Margin: Window ⇒ Preferences ⇒ General ⇒ Editors ⇒ Text Editors ⇒ Show Print Margin and set the column number.
  25. Let me know if you have more tips to be included here.

7.  Writing Swing Applications using Eclipse GUI Builder

Eclipse provides a visual GUI builder called "WindowBuilder" (@ https://www.eclipse.org/windowbuilder), which supports AWT/Swing, SWT (Eclipse's Standard Widget Toolkit - an alternative to JDK's AWT/Swing), XWT, GWT, eRCT.
Step 0: Install WindowBuilder
To install "WindowBuilder", goto "Help" ⇒ Install New Software ⇒ In "Work with", enter "https://download.eclipse.org/windowbuilder/latest/" (You can find the proper link from "http://www.eclipse.org/windowbuilder/download.php") ⇒ Check "WindowBuilder" ⇒ Next ⇒ Next ⇒ Accept the licence ⇒ Finish.
Step 1: Create a New "Java Application" Project
  1. Choose "File" menu ⇒ "New" ⇒ "Java project".
  2. The "New Java Project" dialog pops up.
    1. In the "Project name" field, enter "FirstSwingProject".
    2. Check "Use default location".
    3. In the "JRE" box, select "Use default JRE (currently 'JDK1.x')".
    4. Click "Finish".
Step 2: Create a Swing JFrame Subclass
  1. Choose "File" menu ⇒ "New" ⇒ "Others" ⇒ "WindowBuilder" ⇒ "Swing Designer" ⇒ "JFrame" ⇒ "Next".
  2. In the "Create JFrame" dialog ⇒ Enter "SwingMain" in the "Name" field ⇒ "Finish".
  3. Select the "Design" pane.
  4. In "Layouts", select "FlowLayout" and click on the "design form".
  5. From "Components", select "JLabel" and click on the design 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 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 event-handler skeleton created. Complete the actionPerformed() as follows:
    public void actionPerformed(ActionEvent e) {
       count++;
       textField.setText(count + "");  // Check the name for the TextField
    }
    Add an instance variable called count as follow:
    public class SwingMain extends JFrame {
       private int count = 0;
       ......
  7. You can now ready run the program. Right-click on the project ⇒ Run As ⇒ Java Application.
Eclipse Generated Codes
Study the codes generated by Eclipse GUI Builder, as follows, which is just a typical Swing application.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
 
public class SwingMain extends JFrame {  // A JFrame application
 
   // Define private variables of all the GUI components
   private JPanel contentPane;
   private JTextField textField;
   private int count = 0;
 
   /**
    * Launch the application.
    */
   public static void main(String[] args) {
      EventQueue.invokeLater(new Runnable() {  // same as SwingUtilities.invokeLater()
         @Override
         public void run() {
            try {
               SwingMain frame = new SwingMain();
               frame.setVisible(true);
            } catch (Exception e) {
               e.printStackTrace();
            }
         }
      });
   }
 
   /**
    * Create the frame.
    */
   public SwingMain() {
      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);
   }
}



10.  Eclipse and Database Development (MySQL)

Reference: "Data Tools Platform User Documentation" @ Eclipse Welcome page.
You need to install Eclipse for Java EE, MySQL and MySQL Connector/J Driver. Read "How to install and get started with MySQL".
To use Eclipse for MySQL development:
  1. Switch to "Database Development" perspective: From "Window" menu ⇒ Open Perspective ⇒ Other ⇒ Database Development.
  2. Connect to MySQL database server: Start your MySQL database server. Right-click "Database Connection" ⇒ New.
    1. In "Connection Profile", choose "MySQL" ⇒ Next.
    2. In "Driver", choose "New Driver Definition" ⇒ Choose the MySQL Connector/J Driver ⇒ In JAR List, select the MySQL Connector/J Driver JAR file (that you have installed). In "Properties", "General", specify URL (take note of the database name), User name and password ⇒ Test Connection ⇒ Finish.
    3. In "Datasource Explorer", you can "connect" and "disconnect" the connection.
  3. 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".
  4. 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 ...".
  5. 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.

Configure LOG4J in INTELLIJ in Windows.

IntelliJ debugger for temporary logging In this video, it is shown how to use Log4j in Intellij. Sorry for the audio quality :) Log4j zip fi...