Run a Java Quickstart in Eclipse

Create Java console programs and a Swing click counter in Eclipse.

Introduction

30 Second Summary

Java concepts become easier to understand when you can run each idea and inspect the result. A working Console message gives you immediate proof that your code is doing what you intended.

In this project, you will build a Java quickstart created for the Dangal ng Bayans at the University of Cabuyao. Using Eclipse IDE, you will turn Java fundamentals into programs you can run and test.

What You'll Build

You will watch your Java project grow from a Console greeting into a Click Counter window that responds to every button press.

By the end of this project, you'll have:

  • A working Java project in Eclipse where you can create classes and inspect each result in the Console.
  • Three Console challenges that let you calculate values, test a pass or fail decision, and find the largest number.
  • A Swing Click Counter that updates its label whenever you press Count Click.
  • Secret Mission: Add a Reset button that returns the counter to zero while preserving its increment action.

Do I need Java experience?

Some prior coding experience helps. No Java experience is required.

This workshop assumes Eclipse IDE and a Java Development Kit are already installed on Windows. Step 1 starts with a brief Java introduction before you create the project.

Before We Start

Before you start coding, lock in what you are about to build and why each challenge matters. This gives every program a clear purpose before you open Eclipse.

Set Up Eclipse and Live-Code Java Essentials

Set Up Eclipse and Run Your First Java Program

Java organizes program behavior inside classes. Eclipse IDE lets you run those classes and inspect their Console output.

You will start by creating one Eclipse project for the workshop. Its workshop package keeps each challenge class together.

In this step, get ready to:
  • Create the JavaQuickstart project in Eclipse.
  • Organize your code in the workshop package.
  • See HelloJava.java print its first Console output.
Create your Java project
  • Press the Windows key to open Windows search.
  • Type Eclipse.
  • Press Enter to open Eclipse.
  • Keep the suggested workspace location if Eclipse asks you to choose one.

You should see the Eclipse workspace. You are ready to create the project that holds your Java classes.

A Java project gives Eclipse one place to compile your files. A package groups the related classes under the name workshop.

  • Select File from the Eclipse menu bar.
  • Select New.
  • Select Java Project.
  • Enter JavaQuickstart in the Project name field.
  • Keep Use default JRE selected.
  • Click Finish.

The Package Explorer should now list JavaQuickstart. Your Java project is ready to hold the classes you create next.

  • Expand JavaQuickstart in the Package Explorer.
  • Right-click the src source folder.
  • Select New.
  • Select Package.
  • Enter workshop in the Name field.
  • Click Finish.

The workshop package should appear beneath src.

  • Right-click the workshop package.
  • Select New.
  • Select Class.
  • Enter HelloJava in the Name field.
  • Confirm that the Package field shows workshop.
  • Select the public static void main(String [] args) method stub.
  • Click Finish.

Eclipse opens HelloJava.java in the editor. The generated class already has the entry point required for a Java application.

Cannot Create the Java Elements?

Confirm that you created a Java project. A general project does not provide the Java package or class wizards.

Select the src folder before creating the package. Select the workshop package before creating the class.

Ask for help with creating the Eclipse project structure.

Run the Java essentials

A Java class groups the program code. The main method gives Java the starting point for execution.

This first runnable slice introduces variables with different data types. A condition controls whether the readiness message appears.

  • Replace the generated contents of HelloJava.java with this first runnable slice:
package workshop;

public class HelloJava {
    public static void main(String[] args) {
        String participantName = "Sam";
        int completedChallenges = 0;
        boolean readyToCode = true;

        System.out.println("Hello, " + participantName + "!");
        System.out.println("Completed challenges: " + completedChallenges);

        if (readyToCode) {
            System.out.println("Java workshop ready.");
        }
    }
}

What Does This Code Do?

  • The HelloJava class gives the program a meaningful name.
  • The main method is the code Java runs first.
  • The three declarations store text, a whole number, and a true-or-false value.
  • The if condition prints the readiness message when readyToCode is true.
  • Save HelloJava.java.
  • Select HelloJava.java in the Package Explorer.
  • Right-click the selected file.
  • Select Run As.
  • Select Java Application.

The Console shows the greeting. It also shows the completed challenge count and readiness message.

You have the first live result ready for the workshop. Participants can now attach Java syntax to output they can see.

The First Run Did Not Work?

Check that HelloJava.java remains inside the workshop package. Confirm that the first line still declares the same package.

Match every opening brace with a closing brace. Check the capitalization of String and System.

Ask for help with diagnosing the first Java run.

A helper method keeps the challenge-plan loop separate from the greeting logic. The loop repeats one print statement with challenge numbers 1 through 3.

  • In HelloJava.java, find this final condition block:
        if (readyToCode) {
            System.out.println("Java quickstart ready.");
        }

Where Does the New Logic Go?

This condition is the final block inside main. The challenge-plan call belongs directly beneath it.

  • Replace the two closing braces beneath that condition with this final section:

        printChallengePlan(3);
    }

    private static void printChallengePlan(int totalChallenges) {
        for (int challengeNumber = 1; challengeNumber <= totalChallenges; challengeNumber++) {
            System.out.println("Challenge " + challengeNumber + " is waiting.");
        }
    }
}

What Does This Addition Do?

  • The printChallengePlan(3) call asks the helper method to print three challenge lines.
  • The totalChallenges parameter receives the requested total.
  • The for loop changes challengeNumber after each pass.
  • The loop stops after printing the third challenge line.

Use this comparison to confirm that every declaration and brace is in the correct place.

✔️ Awesome, I've got everything!

Your file now contains the greeting logic and the challenge-plan helper. Continue to the final Console check.

ⓧ I'd like to double check the full code

package workshop;

public class HelloJava {
    public static void main(String[] args) {
        // Store the values shown in the Console.
        String learnerName = "Sam";
        int completedChallenges = 0;
        boolean readyToCode = true;

        // Print the learner's current progress.
        System.out.println("Hello, " + learnerName + "!");
        System.out.println("Completed challenges: " + completedChallenges);

        if (readyToCode) {
            System.out.println("Java quickstart ready.");
        }

        printChallengePlan(3);
    }

    // Print one line for each upcoming challenge.
    private static void printChallengePlan(int totalChallenges) {
        for (int challengeNumber = 1; challengeNumber <= totalChallenges; challengeNumber++) {
            System.out.println("Challenge " + challengeNumber + " is waiting.");
        }
    }
}
How Should I Use This Reference?

Compare the package declaration, class body, and method braces with your editor. The complete file should match this reference exactly.

One-Screen Java Syntax Reference

  • A class declaration names the program structure with public class HelloJava.
  • The main method marks the program's starting point.
  • A variable declaration places the data type before the variable name.
  • The if block runs when its condition is true.
  • The for loop repeats while its comparison remains true.
  • The printChallengePlan method packages reusable behavior behind a meaningful name.

💡 Keep the Live Code Paced

  • Type one logical section at a time during the workshop.
  • Name HelloJava when you type the class declaration.
  • Identify main as the entry point.
  • Pause at each variable declaration to name its data type.
  • Ask participants what controls the readiness message.
  • Trace challengeNumber through the loop.
  • Present printChallengePlan as a helper method with one responsibility.

Before you run the finished class, what do you expect the final three Console lines to number?

  • Save HelloJava.java.
  • Return to HelloJava.java in the Package Explorer.
  • Right-click the selected file.
  • Select Run As.
  • Select Java Application.

What Should I See?

The first two Console lines are Hello, Sam! and Completed challenges: 0.

The next line is Java workshop ready..

The final lines are Challenge 1 is waiting., Challenge 2 is waiting., and Challenge 3 is waiting..

🙋‍♀️ Challenge Lines Missing?

Confirm that printChallengePlan(3) remains inside main. Check that the helper method remains inside HelloJava.

Check the spelling of printChallengePlan in both locations. Java treats different capitalization as different names.

Ask for help with restoring the challenge-plan output.

That is your immediate workshop win. Eclipse can compile the class and display every planned Console line.

Your workshop project now runs in Eclipse. Next, participants will use arithmetic to produce their first challenge result.

Build a Simple Calculator

Your first Java program now runs in Eclipse IDE. The next challenge turns stored numbers into visible calculations.

Arithmetic gives you a result you can inspect immediately. A separate class keeps this challenge independent from HelloJava.

In this step, get ready to:
  • Create a runnable CalculatorChallenge class in the workshop package.
  • Calculate four results with whole-number variables.
  • Run the calculator to investigate how division behaves.
Create the calculator class

Each challenge needs its own runnable entry point. This lets you test the calculator without changing the program you completed earlier.

  • In the workshop package from earlier, launch the New Java Class wizard.
  • Enter CalculatorChallenge as the class name.
  • Select the option that adds a main method stub.
  • Complete the wizard.

Eclipse opens CalculatorChallenge.java with a matching class declaration. The file also contains a main method where the calculations can run.

Write the arithmetic program

The int data type stores whole numbers. Four result variables make each arithmetic operation easy to print and compare.

  • Replace the generated contents of CalculatorChallenge.java with the code below:
package workshop;

public class CalculatorChallenge {
    public static void main(String[] args) {
        int firstNumber = 7;
        int secondNumber = 2;

        int additionResult = firstNumber + secondNumber;
        int subtractionResult = firstNumber - secondNumber;
        int multiplicationResult = firstNumber * secondNumber;
        int divisionResult = firstNumber / secondNumber;

        System.out.println("Addition: " + additionResult);
        System.out.println("Subtraction: " + subtractionResult);
        System.out.println("Multiplication: " + multiplicationResult);
        System.out.println("Division: " + divisionResult);
    }
}

What Does This Code Do?

  • The package workshop; line keeps the calculator beside the earlier class.
  • The main method gives Eclipse a starting point for the program.
  • The firstNumber variable stores 7. The secondNumber variable stores 2.
  • The four arithmetic operators calculate addition, subtraction, multiplication, and division results.
  • Each System.out.println statement gives one result its own Console line.
  • Save CalculatorChallenge.java.
  • Review the editor margin for problem markers.

The editor should show no problem markers beside CalculatorChallenge.java. The class is ready to run.

Seeing Problems in the Editor?

Confirm that CalculatorChallenge.java matches the CalculatorChallenge class name exactly.

Check that each statement ends with a semicolon. Match every variable name with the capitalization shown above.

Ask for targeted help with diagnosing the calculator code.

✔️ Awesome, I've got everything!

Your saved calculator contains two inputs, four calculations, and four Console output lines.

ⓧ I'd like to double check the full code

package workshop;

public class CalculatorChallenge {
    public static void main(String[] args) {
        int firstNumber = 7;
        int secondNumber = 2;

        int additionResult = firstNumber + secondNumber;
        int subtractionResult = firstNumber - secondNumber;
        int multiplicationResult = firstNumber * secondNumber;
        int divisionResult = firstNumber / secondNumber;

        System.out.println("Addition: " + additionResult);
        System.out.println("Subtraction: " + subtractionResult);
        System.out.println("Multiplication: " + multiplicationResult);
        System.out.println("Division: " + divisionResult);
    }
}

What Should Match?

All calculator logic sits inside the main method. The two inputs produce four separate Console lines.

Build One Operation at a Time

  • Use the addition expression as your pattern for the remaining operations.
  • Complete subtraction, multiplication, and division one at a time.
  • Open the full-code tab if a syntax or naming error blocks your progress.
Run the integer calculation

Running the class tests all four expressions with the same two values. The division line reveals how whole-number arithmetic handles a fractional result.

Before you run it, predict the value the division line will show.

  • Select CalculatorChallenge.java in Eclipse.
  • Choose Run As.
  • Choose Java Application.

The Console shows Addition: 9. It also shows Subtraction: 5.

The next line shows Multiplication: 14. The final line shows Division: 3.

Your first challenge is running. You now have a four-line checkpoint that makes every arithmetic result visible.

Why Is the Division Result 3?

Both firstNumber and secondNumber use int. This data type stores whole numbers.

Java applies integer division when both operands are integers. The decimal portion is discarded, so the Console shows 3.

  • Explain the missing decimal portion in your own words before you move to the correction.

That visible precision gap has done its job. Next, you will correct it. You will also turn stored values into a pass-or-fail decision.

Fix Division and Check Pass or Fail

Your last calculator run exposed a precision gap in Java. The Console showed Division: 3 because both values used whole-number types.

This step fixes that calculation with decimal values. You will also build a conditional that turns a score into a pass or fail result.

In this step, get ready to:
  • Change the calculator's numeric declarations to double.
  • Build PassFailChallenge with an if/else decision.
  • Test the decision across its pass mark.
Fix the calculator's precision

The int type stores whole numbers. Division between two int values removes the fractional portion before Java stores the result.

  • Return to CalculatorChallenge.java in the Eclipse editor.
  • Find the eight variable declarations that begin with int.
  • Replace the int type keyword with double across those declarations.
  • Compare your edited declarations with this code:
        double firstNumber = 7;
        double secondNumber = 2;

        double additionResult = firstNumber + secondNumber;
        double subtractionResult = firstNumber - secondNumber;
        double multiplicationResult = firstNumber * secondNumber;
        double divisionResult = firstNumber / secondNumber;

What Does This Change Do?

  • The double type can store fractional values.
  • Changing both input variables makes Java perform decimal division.
  • The result variables now store the decimal outputs produced by each calculation.
  • Save CalculatorChallenge.java.
  • Select CalculatorChallenge.java in the Package Explorer.

Before you run the calculator, what division result do you expect from 7 divided by 2 now?

  • Select Run in Eclipse's top menu.
  • Select Run As.
  • Select Java Application.

The Console now shows Division: 3.5. That precision gap is fixed because the calculation uses decimal values.

Still Seeing Division: 3?

Check that both firstNumber and secondNumber use double. Confirm that you ran CalculatorChallenge.java.

Ask for targeted help with debugging the calculator's decimal division.

✔️ Awesome, I've got everything!

Great work. Save CalculatorChallenge.java before moving to the next challenge.

ⓧ I'd like to double check the full code

package workshop;

public class CalculatorChallenge {
    public static void main(String[] args) {
        double firstNumber = 7;
        double secondNumber = 2;

        double additionResult = firstNumber + secondNumber;
        double subtractionResult = firstNumber - secondNumber;
        double multiplicationResult = firstNumber * secondNumber;
        double divisionResult = firstNumber / secondNumber;

        System.out.println("Addition: " + additionResult);
        System.out.println("Subtraction: " + subtractionResult);
        System.out.println("Multiplication: " + multiplicationResult);
        System.out.println("Division: " + divisionResult);
    }
}
Build the pass or fail decision

A conditional chooses a path from a comparison. This challenge compares a score with the required passMark.

  • Right-click the workshop package in the Package Explorer.
  • Select New.
  • Select Class.
  • Enter PassFailChallenge in the Name field.
  • Select the checkbox that adds the main method stub.
  • Click Finish.
  • Replace the generated class content by pasting this code:
package workshop;

public class PassFailChallenge {
    public static void main(String[] args) {
        int score = 72;
        int passMark = 60;

        System.out.println("Score: " + score);

        if (score >= passMark) {
            System.out.println("Result: Pass");
        } else {
            System.out.println("Result: Fail");
        }
    }
}

What Does This Code Do?

  • The score variable stores the result being checked.
  • The passMark variable stores the passing boundary.
  • The score >= passMark comparison selects the pass branch for an equal or higher score.
  • The else branch handles every score below the boundary.
  • Save PassFailChallenge.java.
  • Select PassFailChallenge.java in the Package Explorer.

Before you run the challenge, which branch should a score of 72 select?

  • Select Run in Eclipse's top menu.
  • Select Run As.
  • Select Java Application.

The Console shows Score: 72. It then shows Result: Pass.

PassFailChallenge Does Not Run?

Check that the class name matches PassFailChallenge. Confirm that every opening brace has a matching closing brace.

Ask for targeted help with debugging the pass or fail condition.

Test both sides of the condition

A decision needs checks at its boundary. Testing an equal value reveals whether the comparison includes the pass mark.

  • Replace the 72 assigned to score with 60.
  • Save PassFailChallenge.java.
  • Select PassFailChallenge.java in the Package Explorer.

At the exact pass mark, do you expect the pass branch or the fail branch to run?

  • Select Run in Eclipse's top menu.
  • Select Run As.
  • Select Java Application.

The Console shows Result: Pass for a score of 60.

Compare the Boundary Operators

  • Read >= as greater than or equal to.
  • Compare it with >, which excludes a score equal to the boundary.
  • Use the Console result to confirm why a score of 60 passes.
  • Replace the 60 assigned to score with 48.
  • Save PassFailChallenge.java.
  • Select PassFailChallenge.java in the Package Explorer.

Before you run the challenge again, which branch should handle a score below 60?

  • Select Run in Eclipse's top menu.
  • Select Run As.
  • Select Java Application.

The Console shows Score: 48. It then shows Result: Fail.

  • Restore the score value from 48 to 72.
  • Save PassFailChallenge.java.
  • Select PassFailChallenge.java in the Package Explorer.

For the final check, which result should the restored score produce?

  • Select Run in Eclipse's top menu.
  • Select Run As.
  • Select Java Application.

The Console returns to Score: 72 followed by Result: Pass. You have now proved that both branches work.

Seeing the Wrong Result?

Check that the comparison reads score >= passMark. Confirm that the displayed score matches the value you intended to test.

Ask for targeted help with tracing the if and else branches.

✔️ Awesome, I've got everything!

Your challenge handles passing scores, failing scores, and the exact boundary. Keep the final score value at 72.

ⓧ I'd like to double check the full code

package workshop;

public class PassFailChallenge {
    public static void main(String[] args) {
        int score = 72;
        int passMark = 60;

        System.out.println("Score: " + score);

        if (score >= passMark) {
            System.out.println("Result: Pass");
        } else {
            System.out.println("Result: Fail");
        }
    }
}

Your calculator now preserves decimal precision. Next, you will combine arrays, loops, comparisons, and a method to find the largest number.

Find and Sort the Largest Number

Your calculator now preserves decimal precision. Your pass-or-fail class turns a score into a decision.

Your Eclipse IDE project is ready for a challenge that combines stored values with repeated comparison. A Java array feeds a manual maximum search before the standard library sorts the same values.

In this step, get ready to:
  • Create a runnable largest-number challenge around an integer array.
  • Trace how the maximum search handles every array value.
  • Sort the same values into ascending order.
Build the manual maximum search

One fixed set of values gives you a consistent result while you trace the search. A helper method keeps the search logic separate from the program entry point.

  • Select workshop in the project sidebar from earlier.
  • Open the New Java Class wizard for the selected package.

You'll see the class wizard for the existing workshop package.

  • Enter LargestNumberChallenge as the class name.
  • Enable the public static void main(String [] args) stub.

The wizard now has the package, class name, and entry point needed for a runnable challenge.

  • Create the class.

You'll see LargestNumberChallenge.java inside the workshop package.

  • Replace the generated contents of LargestNumberChallenge.java by pasting the code below:
package workshop;

import java.util.Arrays;

public class LargestNumberChallenge {
    public static void main(String[] args) {
        int[] numbers = {12, 5, 27, 9, 18};

        int largestNumber = findLargest(numbers);
        System.out.println("Largest number: " + largestNumber);
    }

    private static int findLargest(int[] numbers) {
        int largestNumber = numbers[0];

        for (int number : numbers) {
            if (number > largestNumber) {
                largestNumber = number;
            }
        }

        return largestNumber;
    }
}

What Does This Code Do?

  • The numbers array holds the five values used throughout the challenge.
  • The findLargest(numbers) call passes those values into the search method.
  • The numbers[0] value gives the search a real starting candidate.
  • The enhanced for loop visits each number.
  • The comparison replaces largestNumber whenever the loop finds a higher value.
  • Save LargestNumberChallenge.java.

Before you run the class, which value do you expect the loop to keep?

  • Select LargestNumberChallenge.java.
  • Choose Run As.
  • Choose Java Application.

Your manual search is working. The Console shows Largest number: 27.

Largest Number Missing?

Check that main calls findLargest(numbers). Confirm that the method returns largestNumber after the loop.

Ask for targeted help with debugging the manual maximum search.

Test the starting-value assumption

The initial candidate determines whether the method begins with a value that actually exists in the array. This choice becomes important when every number is negative.

  • Predict what an all-negative array would return if the starting maximum were 0.
  • Locate numbers[0] inside findLargest.
  • Connect the first array value to the valid candidate used before the loop begins.

An initial value of 0 could produce a result that never appeared in an all-negative array. Starting from numbers[0] keeps the result grounded in the supplied data.

Sort the same values

The manual method answers the maximum question directly. The Arrays.sort(numbers) call demonstrates a reusable library operation that changes the array into ascending order.

  • Locate the System.out.println("Largest number: " + largestNumber); line in LargestNumberChallenge.java.
  • Add the sorting block directly below that line by pasting this code:
        Arrays.sort(numbers);
        System.out.print("Sorted values: ");
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        System.out.println();

What Does This Code Do?

  • The Arrays.sort(numbers) call rearranges the existing array into ascending numerical order.
  • The enhanced for loop prints each sorted value.
  • The final System.out.println() call moves the Console cursor to a new line.
  • Save LargestNumberChallenge.java.

✔️ Awesome, I've got everything!

The manual search and sorting logic are both present in your saved class.

ⓧ I'd like to double check the full code

package workshop;

import java.util.Arrays;

public class LargestNumberChallenge {
    public static void main(String[] args) {
        int[] numbers = {12, 5, 27, 9, 18};

        int largestNumber = findLargest(numbers);
        System.out.println("Largest number: " + largestNumber);

        Arrays.sort(numbers);
        System.out.print("Sorted values: ");
        for (int number : numbers) {
            System.out.print(number + " ");
        }
        System.out.println();
    }

    private static int findLargest(int[] numbers) {
        int largestNumber = numbers[0];

        for (int number : numbers) {
            if (number > largestNumber) {
                largestNumber = number;
            }
        }

        return largestNumber;
    }
}

This reference shows the exact completed class for comparison.

Before you run the final check, which line do you expect the Console to print second?

  • Select LargestNumberChallenge.java.
  • Choose Run As.
  • Choose Java Application.

The Console shows Largest number: 27 first. The next line reads Sorted values: 5 9 12 18 27.

That is the full challenge working: the Console proves both operations.

Sorted Values Missing?

Confirm that Arrays.sort(numbers) appears before the printing loop. Check that import java.util.Arrays; remains below the package declaration.

Ask for help with debugging the sorting checkpoint.

Your challenge now combines the core console skills in one runnable class. Next, you will make Java respond to a button click in a window.

Preview a Swing Click Counter

Your largest-number challenge now finds the maximum with a loop. It also sorts the same array with Java's standard library.

You are ready to move from console output to Java's event-driven model. Swing lets a button event change stored state inside a window.

In this step, get ready to:
  • Create a Click Counter that launches in a Swing window.
  • Connect the Count Click button to shared counter state.
  • Trace the state variable, event source, and visible output from one click.
Create the Click Counter window

A Swing app schedules its interface on the event-dispatch thread. SwingUtilities.invokeLater starts that work from the program's main method.

You will build the window in stages so every change produces something visible. Start with a runnable shell before you add its label and button.

  • In Eclipse, right-click the workshop package.
  • Open the New Java Class wizard.
  • Enter ClickCounter as the class name.
  • Create the class.

You should see ClickCounter.java inside the workshop package. The Click Counter now has its own runnable class.

  • Replace the generated contents of ClickCounter.java by pasting this window shell:
package workshop;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ClickCounter {
    private static int clickCount = 0;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Java Click Counter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

What Does This Code Do?

  • The clickCount field stores one counter value for the class.
  • The main method schedules the interface through SwingUtilities.invokeLater.
  • The createAndShowGui method creates the window.
  • The final three calls size, center, and display the window.
  • Save ClickCounter.java.
  • Select ClickCounter.java in the package tree.
  • Open Run As from the context menu.
  • Select Java Application.

You should see a compact window titled Java Click Counter. The window proves the Swing interface launches from the new class.

  • Close the Java Click Counter window.

Window Did Not Open?

Check that the file is named ClickCounter.java. Confirm that the class declaration uses ClickCounter.

Compare the braces around main and createAndShowGui with the code above.

Ask for targeted help with diagnosing why the Swing window does not open.

Add the counter controls

A JPanel groups the window's components. The JLabel displays state while the JButton provides the event source.

  • In ClickCounter.java, find the line containing frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);.
  • Find frame.pack(); below it.
  • Paste this component block between those two lines:
        JPanel panel = new JPanel();
        JLabel countLabel = new JLabel("Clicks: 0");
        JButton countButton = new JButton("Count Click");

        panel.add(countLabel);
        panel.add(countButton);
        frame.add(panel);

What Do These Components Do?

  • The panel holds the window's components.
  • The countLabel displays the current total.
  • The countButton gives participants a visible event source.
  • The frame.add(panel) call places the component group inside the window.
  • Save ClickCounter.java.
  • Select ClickCounter.java in the package tree.
  • Open Run As from the context menu.
  • Select Java Application.

You should see Clicks: 0 beside a Count Click button. The interface now exposes both the stored state and its event source.

  • Close the Java Click Counter window.

Controls Missing From the Window?

Confirm that the component block sits before frame.pack();. The frame calculates its size from components that have already been added.

Check that both panel.add calls appear before frame.add(panel).

Ask for help with finding missing Swing controls.

Wire and trace the click event

An action listener runs when the button produces an event. The listener changes clickCount before refreshing countLabel.

  • In ClickCounter.java, find the countButton declaration.
  • Place the cursor on the blank line below that declaration.
  • Insert the button listener by pasting this code:
        countButton.addActionListener(event -> {
            clickCount++;
            countLabel.setText("Clicks: " + clickCount);
        });

Trace One Button Click

  • The countButton is the event source.
  • The addActionListener call connects the button to its response.
  • The clickCount field stores the updated state.
  • The countLabel.setText call turns that state change into visible output.
  • Save ClickCounter.java.
  • Select ClickCounter.java once in the package tree without opening its source.

Before you launch the final demo, which value do you expect the button event to change?

  • Open Run As from the context menu.
  • Select Java Application.
  • Click Count Click three times.

After the third click, you'll see Clicks: 3. The event has changed shared state before refreshing the visible label.

You now have the workshop's final demonstration working. Participants can trace the same variables and methods they used in the console challenges through a clickable interface.

Label Stays at Zero?

Confirm that the listener belongs to countButton. Check that clickCount++ appears inside its braces.

Verify that countLabel.setText uses the same clickCount field declared near the top of the class.

Ask for help with tracing the button listener.

Your completed ClickCounter.java file should match the reference below.

✔️ Awesome, I've got everything!

Your Click Counter opens with Clicks: 0. Three button clicks update the label to Clicks: 3.

ⓧ I'd like to double check the full code

package workshop;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ClickCounter {
    private static int clickCount = 0;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("Java Click Counter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        JLabel countLabel = new JLabel("Clicks: 0");
        JButton countButton = new JButton("Count Click");

        countButton.addActionListener(event -> {
            clickCount++;
            countLabel.setText("Clicks: " + clickCount);
        });

        panel.add(countLabel);
        panel.add(countButton);
        frame.add(panel);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Secret mission

Add a Reset Button

Add a Reset control to the existing Click Counter. Reuse clickCount for both actions. Keep countLabel synchronized after every click.

Clean Up Your Resources

Clean Up Your Resources

Your Eclipse workshop runs entirely on your Windows computer, so it creates no ongoing charges. Choose whether to keep the JavaQuickstart project ready, close it for now, or remove it completely.

Resources you used:

  • The local JavaQuickstart project with the workshop package.
  • Five Java source files named HelloJava.java, CalculatorChallenge.java, PassFailChallenge.java, LargestNumberChallenge.java, and ClickCounter.java.

Keep everything running

No action needed. Choose this if you want to rehearse the workshop or adapt its challenges for another audience.

  • Keep the JavaQuickstart project available in Eclipse.
  • Keep the five source files as your participant examples and instructor solutions.

Your console challenges and Click Counter remain ready to run during your next workshop.

Pause - I'll come back to this later

Close the running programs to free up memory. Your completed workshop project remains stored on your computer.

  • Close the Java Click Counter window if it is still running.
  • Return to Eclipse from earlier.
  • Save any open Java source files.
  • Close Eclipse.

The Click Counter and Eclipse stop using memory. The JavaQuickstart project remains available for your next session.

Delete - I don't want to use this again

A full reset permanently removes the workshop code from your computer. Eclipse and Java stay installed for future projects.

  • Close the Java Click Counter window if it is still running.
  • Return to Eclipse from earlier.
  • Select JavaQuickstart in Eclipse's project list.
  • Press the Delete key.
  • Choose the deletion option that removes the project contents from disk.
  • Confirm the project deletion.

You no longer see JavaQuickstart in Eclipse. Cleanup complete: its five workshop source files are also removed from disk.

Nice Work!

Nice Work!

You did it. You now have a complete beginner Java workshop that moves participants from their first program in Eclipse IDE to an event-driven GUI.

You've learned how to:

  • Facilitate a 45-minute Java workshop that moves participants from their first class to a working Click Counter.
  • Teach console problem-solving through three progressive challenges. Participants see integer division lose precision. They fix it with double. They use if with else to make a decision. They compare findLargest with Arrays.sort.
  • Demonstrate Swing event handling with a Click Counter. Participants can trace clickCount from a button event to the updated label.
  • Secret Mission: Extend the Click Counter with a second button. The Reset action changes clickCount to 0. The label updates to Clicks: 0.

Ready to quiz yourself? Let's check what stayed with you.