Eclipse Creating Java Class

Till now we have learnt about the following important topics -

In this chapter we will be learning how to create a Java class

Eclipse Creating Java Class

We can create the Java Class using the following 3 different ways -

  1. By clicking on the File menu and choosing New > class
  2. By right clicking anywhere in the Project Explorer and selecting New > class
  3. By clicking on the New button (Eclipse Creating Java Class - icon) in the Tool bar and selecting class

Steps for creating Java class

Right click on the package explorer in the Eclipse Workspace and then select the class option

Eclipse Creating Java Class

After selecting the class icon we need to fill following information that we have listed in the table -

Eclipse New class name window

FieldExplanation
Source/Folder NameProvide the correct source name
PackageProvide the appropriate package name
NameProvide the class name with first letter as capital letter
Method StubsIf you want to create the main method by default then just check the respective check box
CommentsIf you want to generate the default comment then select the check box.

After the creation of the class we can see how class is created in the eclipse -

Viewing class in eclipse

Eclipse Creating Java Package

Once we create a Java Project in Eclipse, we might want to create a java package in Eclipse IDE. It can be achieved using the three ways -

Eclipse Creating Java Package

We can create the Java Project using the following 3 different ways -

  1. By clicking on the File menu and choosing New > Package
  2. By right clicking anywhere in the Project Explorer and selecting New > Package
  3. By clicking on the New button (Select Java Package ) in the Tool bar and selecting Package

Steps to create Package

Right click on the package explorer in the Eclipse Workspace and then select the package option

Creating Java Package in Eclipse

Once you select the package option then you will be prompted with the below screen

Eclipse Naming Java Package

You need to name your Java package which should not contain the space or dot at the last. Otherwise it will provide you following error message - Invalid package name. A package name cannot start or end with a dot

Invalid Java Package Name

Once we create package then we can see it inside the package explorer like this -

Eclipse Viewing Package

Eclipse Creating Java Project

In this tutorial we will be learning how to create a sample Java project in the Eclipse IDE.

Eclipse Creating Java Project

We can create the Java Project using the following 3 different ways -

  1. By clicking on the File menu and choosing New > Java Project
  2. By right clicking anywhere in the Project Explorer and selecting New > Java Project
  3. By clicking on the New button (new project icon ) in the Tool bar and selecting Java Project

Steps to create project

Step 1 - Create new Java Project

Now when we select Java Project as option then we below window gets opened.

Step 2 - Name Java Project Eclipse

Give proper name to your Java Project. Project name should not contain space.

Step 3 - Provide Project Setting

Just keep these settings as it is and click on the next button to proceed further

Step 4 - Perspective

It would then prompt user with message saying that your project will be opened in the Java Perspective.

Step 5 - Java Project Created

After clicking on the finish button your project will be created in the Workspace.

Eclipse IDE Workspace

When we start the project then we need to open a folder where your code or project resides. Folder which is used for the development is called workspace

Eclipse IDE Workspace

Workspace of the Eclipse is nothing but the collection of the files arranged inside the defined directory structure. Workspace contains following resources -

  1. Projects
  2. Source/Configuration of any type of File
  3. Folders/directories

Workspace is arranged in hierarchical structure. Projects are at the top level of the hierarchy and inside them all the files and folders are listed

Eclipse Workspace Tree

You can see all the resources are arranged in the tree or hierarchical fashion.

Creating folder in Workspace

Now we are going to create a folder in the workspace which is used to store all the assets that we are using inside the project

Create folder in Eclipse Workspace

Now give proper name to folder in the Workspace. See below screenshot

Naming folder name

Now you will be able to see the folder created inside the workspace.

View created folder

Eclipse IDE Views

Eclipse IDE contains the number of views which are useful during development to get idea of project workspace and hierarchy of the project

Eclipse IDE Menubar

We know IDE is used to create the code in professional manner and efficiently. During the process of coding we may find certain views in the code that are very useful. It is used to show the graphical representations of the project metadata.

Eclipse Views

If you carefully observe the above screenshot then you can understand there are 5 views in the eclipse window -

Repositioning Views :

We can reposition all the views in the eclipse just by dragging it to the other positions. Possible place holders would be displayed using the green border as shown in below screenshot

Eclipse Repositioning Views

Opening a view

Now suppose you want to open the new view that is not present inside the default list of views then we can do following steps.

Eclipse Show View Option

If you did not find the view that you are looking for then just click on the other menu item.

Eclipse Open Other Views

Eclipse IDE Menubar

Like other IDE we can find there is top toolbar in Eclipse IDE. We can use this toolbar to navigate between different menus.

Eclipse IDE Menubar

Below is the list of the menus available in the Eclipse IDE Window -

  1. File menu
  2. Edit menu
  3. Navigate menu
  4. Search menu
  5. Project menu
  6. Run menu
  7. Window menu
  8. Help menu

Eclipse IDE Toolbar

Menu NameDescription
FileFile menu is used to open files for opening, editing, closing, saving the contents of file. It also provides the rename facilities along with switching workspace. It also allows you to import and export workspace content and shut down Eclipse.
EditIt provides editing options such as copy & paste.
NavigateIt provides the quick navigate menus used for quickly locating the resources.
SearchSearch menu provides different ways to search the workspace for files and text.
ProjectProject menu provides different options used for building a project , building workspace and cleaning workspace.
RunRun menu used to run program and debug it using debug mode.
WindowWindow menu allows you to open and close views and perspectives.
HelpHelp menu used to open Help window, Eclipse Marketplace view or Install new plug-ins. The about Eclipse menu item gives you version information.
SourceOnly visible when Java editor is open. It provides options for editing Java source code.

Eclipse IDE Windows : Views

After setting up the eclipse we need to open the eclipse. Upon launching the eclipse window we find some of the visible screens.

Eclipse IDE Windows : Views

Some of the visible areas of the Eclipse IDE are -

  1. Editor Views
  2. Code Editors
  3. Menu Bar
  4. Toolbar

Eclipse Windows and Views

Eclipse Perspective

  1. If you see carefully at the title bar of the eclipse window , you will find the name of the eclipse perspective.
  2. Initial collection and arrangement of the eclipse windows and views is called as Eclipse perspective.
  3. Though we can have multiple prospectives but at a time only one perspective can be visible.

Some of the eclipse perspectives are -

PerspectiveExplanation
DebugPerspective used while debugging the code
JavaPerspective used while writing the code
WebPerspective used in web project

Opening new Eclipse window

We can open the new eclipse window using Window -> New Window option.

Eclipse Opening new window

So we can have two instances of the eclipse and we can have different perspective in each window

Swing Focus Adapter

Swing Focus Adapter

  1. FocusAdapter class is an abstract adapter class in Java Swing.
  2. FocusAdapter class is for receiving keyboard focus events.
  3. Methods specified in FocusAdapter class are empty.
  4. FocusAdapter class exists as convenience for creating listener objects

Class declaration

Below is the declaration for java.awt.event.FocusAdapter class -

public abstract class FocusAdapter
   extends Object
      implements FocusListener

Class constructors

FocusAdapter()

Class methods

No.MethodReturn TypeParameterInvoked when
1focusGained()voidFocusEventcomponent gains the keyboard focus
2focusLost()voidFocusEventcomponent loses the keyboard focus

Methods inherited

This class inherits methods from the following classes:

java.lang.Object

Swing Focus Adapter Example

AdapterExample.java

package com.c4learn;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AdapterExample {
   private JFrame baseFrame;
   private JLabel headLabel;
   private JLabel msgLabel;
   private JPanel controlPanel;
   public AdapterExample() {
      initializeUI();
   }
   public static void main(String[] args) {
      AdapterExample adapterDemo = new AdapterExample();
      adapterDemo.showFocusApapter();
   }
   private void initializeUI() {
      baseFrame = new JFrame("Java Swing Examples");
      baseFrame.setSize(500, 500);
      baseFrame.setLayout(new GridLayout(3, 1));
      headLabel = new JLabel("", JLabel.CENTER);
      msgLabel = new JLabel("", JLabel.CENTER);
      msgLabel.setSize(300, 100);
      baseFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent) {
            System.exit(0);
         }
      });
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      baseFrame.add(headLabel);
      baseFrame.add(controlPanel);
      baseFrame.add(msgLabel);
      baseFrame.setVisible(true);
   }
   private void showFocusApapter() {
      headLabel.setText("FocusAdapter Example");
      JButton btn1 = new JButton("Button 1");
      JButton btn2 = new JButton("Button 2");
      btn1.addFocusListener(new FocusAdapter() {
         public void focusGained(FocusEvent e) {
            msgLabel.setText("Button 1 - Got focus.");
         }
      });
      btn1.addFocusListener(new FocusAdapter() {
         public void focusLost(FocusEvent e) {
            msgLabel.setText("Button 1 - Lost focus.");
         }
      });
      controlPanel.add(btn1);
      controlPanel.add(btn2);
      baseFrame.setVisible(true);
   }
}

After running program in the eclipse you will see below output

focus adapter

Explanation

In this example consider below two buttons -

JButton btn1 = new JButton("Button 1");
JButton btn2 = new JButton("Button 2");

Now we have added focus listener for the button 1 -

btn1.addFocusListener(new FocusAdapter() {
   public void focusGained(FocusEvent e) {
	msgLabel.setText("Button 1 - Got focus.");
   }
   public void focusLost(FocusEvent e) {
	msgLabel.setText("Button 1 - Lost focus.");
   }
});

Now focusLost() method will provide the code to be executed when button1 will lost its focus. Similarly focusGained() method would be executed when button 1 gains focus.

Swing Key Adapter

Swing Key Adapter

  1. KeyAdapter class is an abstract adapter class in Java Swing.
  2. KeyAdapter class is for receiving keyboard events.
  3. Methods specified in KeyAdapter class are empty.
  4. KeyAdapter class exists as convenience for creating listener objects

Class declaration

Below is the declaration for java.awt.event.KeyAdapter class -

public abstract class KeyAdapter
   extends Object
      implements KeyListener

Class constructors

KeyAdapter()

Class methods

No.MethodReturn TypeParameterInvoked when
1keyPressed()voidKeyEventkey has been pressed
2keyReleased()voidKeyEventkey has been released
3keyTyped()voidKeyEventkey has been typed

Methods inherited

This class inherits methods from the following classes:

java.lang.Object

Key Adapter Example

AdapterExample.java

package com.c4learn;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AdapterExample {
   private JFrame baseFrame;
   private JLabel headLabel;
   private JLabel msgLabel;
   private JPanel controlPanel;
   public AdapterExample() {
      initializeUI();
   }
   public static void main(String[] args) {
      AdapterExample adapterDemo = new AdapterExample();
      adapterDemo.showMouseApapter();
   }
   private void initializeUI() {
      baseFrame = new JFrame("Java Swing Examples");
      baseFrame.setSize(500, 500);
      baseFrame.setLayout(new GridLayout(3, 1));
      headLabel = new JLabel("", JLabel.CENTER);
      msgLabel = new JLabel("", JLabel.CENTER);
      msgLabel.setSize(300, 100);
      baseFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent) {
            System.exit(0);
         }
      });
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      baseFrame.add(headLabel);
      baseFrame.add(controlPanel);
      baseFrame.add(msgLabel);
      baseFrame.setVisible(true);
   }
   private void showMouseApapter() {
      headLabel.setText("KeyAdapter Example");
      final JTextField textField = new JTextField(10);
      JButton displayButton = new JButton("Display");
      displayButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            msgLabel.setText("You entered : " + textField.getText());
         }
      });
      textField.addKeyListener(new KeyAdapter() {
         public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
               msgLabel.setText("You entered : " + textField.getText());
            }
         }
      });
      controlPanel.add(textField);
      controlPanel.add(displayButton);
      baseFrame.setVisible(true);
   }
}

After running program in the eclipse you will see below output

key_adapter

Swing Mouse Adapter

Swing MouseAdapter

  1. MouseAdapter class is an abstract adapter class in Java Swing.
  2. MouseAdapter class is for receiving mouse events.
  3. Methods specified in MouseAdapter class are empty.
  4. MouseAdapter class exists as convenience for creating listener objects

Class declaration

Below is the declaration for java.awt.event.MouseAdapter class -

public abstract class MouseAdapter
   extends Object
      implements MouseListener, 
                 MouseWheelListener, 
                 MouseMotionListener

Class constructors

MouseAdapter()

Class methods

No.MethodReturn TypeParameterInvoked when
1mouseClicked()voidMouseEventmouse button has been clicked
2mouseDragged()voidMouseEventmouse button is pressed on a component and then dragged
3mouseEntered()voidMouseEventmouse enters a component.
4mouseExited()voidMouseEventmouse exits a component.
5mouseMoved()voidMouseEventmouse cursor has been moved onto a component but no buttons have been pushed
6mousePressed()voidMouseEventmouse button has been pressed on a component
7mouseReleased()voidMouseEventmouse button has been released on a component
8mouseWheelMoved()voidMouseEventmouse wheel is rotated.

Methods inherited

This class inherits methods from the following classes:

java.lang.Object

Mouse Adapter Example

AdapterExample.java

package com.c4learn;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AdapterExample {
   private JFrame baseFrame;
   private JLabel headLabel;
   private JLabel msgLabel;
   private JPanel controlPanel;
   public AdapterExample() {
      initializeUI();
   }
   public static void main(String[] args) {
      AdapterExample adapterDemo = new AdapterExample();
      adapterDemo.showMouseApapter();
   }
   private void initializeUI() {
      baseFrame = new JFrame("Java Swing Examples");
      baseFrame.setSize(500, 500);
      baseFrame.setLayout(new GridLayout(3, 1));
      headLabel = new JLabel("", JLabel.CENTER);
      msgLabel = new JLabel("", JLabel.CENTER);
      msgLabel.setSize(300, 100);
      baseFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent) {
            System.exit(0);
         }
      });
      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());
      baseFrame.add(headLabel);
      baseFrame.add(controlPanel);
      baseFrame.add(msgLabel);
      baseFrame.setVisible(true);
   }
   private void showMouseApapter() {
      headLabel.setText("Listener in action : MouseAdapter");
      JPanel panel = new JPanel();
      panel.setBackground(Color.gray);
      panel.setLayout(new FlowLayout());
      JLabel msglabel = new JLabel("www.c4learn.com", JLabel.CENTER);
      msglabel.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
            msgLabel.setText("Mouse Clicked: (" + e.getX() + ", "
                  + e.getY() + ")");
         }
      });
      panel.add(msglabel);
      controlPanel.add(panel);
      baseFrame.setVisible(true);
   }
}

After running program in the eclipse you will see below output

mouse_adapter