ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

Introduction to Event Driven Programming in Java

Updated on June 10, 2009

Event-driven programming is the paradigm on which Java GUIs (graphical user interfaces), C# GUIs and Visual Basic GUIs are based. In this tutorial we introduce the basics of event-driven programming in Java. These concepts carry over to the other languages as well. We create a JFrame object, populate it with a button object and a label object, and put code behind the click event of the button.

In Figure 01 we add a JFrame class to an empty project. The project doesn't have to be empty, but for the sake of clarity it is empty in this example.

Figure 01 - Add a JFrame class to our example project
Figure 01 - Add a JFrame class to our example project

In Figure 02 we give the JFrame class a name. For this example we simply accept the default name and click Finish to complete the process. The Jframe will be the object that contains our controls. Our controls will trigger events. Our code will run when the events trigger.

Figure 02 - Accept the default name for the JFrame
Figure 02 - Accept the default name for the JFrame

Figure 03 illustrates the JFrame class in design view. On the left of the figure is the empty JFrame class. On the right of the figure is the Palette. The Palette provides a menu of controls that can be added to the JFrame. This is much easier than writing code to create controls.

By the way, a great way to learn how to write code to create controls is to use the visual designer, then peek at the code behind the fold. The NetBeans-generated code provides an instant mini-tutorial. Look for the fold icon in the left margin of the Code View.

Figure 03 - The JFrame and the Palette. This is called the "Design View"
Figure 03 - The JFrame and the Palette. This is called the "Design View"

Next, we add one or more controls to the JFrame. For this example we add a button and a label. Click the button in the Palette, then click the location on the JFrame where the button should be created. NetBeans adds the button to the JFrame and generates necessary the Java code.

The button can be dragged and re-sized after dropping it onto the JFrame. It's not necessary to do so here. We aren't concerned about aesthetics at this point.

Next, click on the label in the Palette and click on the JFrame to create a label object. The label on the JFrame can be dragged and re sized.

Figure 04 illiustrates what your JFrame might look like after adding the two controls.

Figure 04 - The JFrame, after adding the button and label controls
Figure 04 - The JFrame, after adding the button and label controls

Much code has been written for us by NetBeans. We are now ready to add some code of our own. Controls on a JFrame have events that take place as your program runs. Some events are widely used and some are almost obscure. For this tutorial we will focus on the Click Event of the button that we added.

We want our code to run when the button is clicked. That's the purpose of a button control.  Therefore, we will put our code into the event handler for the Click Event of the specific button. The Event Handler is simply a method that has been configured to execute when a physical event takes place.

Figure 05 illustrates how to being up the Click Event for the button right-click on the button, select Events / Action / Action Performed.

Figure 05 - Creating the Click Event handler for the button on the JFrame
Figure 05 - Creating the Click Event handler for the button on the JFrame

After creating the Click Event Handler, the Design View will be replaced by the Source View. The Source View is the programming that creates the JFrame. At this point in the process, all the source code has been automagically generated for you by NetBeans. When you added the JFrame class to the project, the code was generated.

Note that an empty method has been created; it's the event handler for the Click Event of the button. That's where our code will go.

Figure 06 displays the Source View and the new event handler.

Figure 06 - The Code View and the newly created Click Event handler
Figure 06 - The Code View and the newly created Click Event handler

The key concept is that whatever code we put in the event handler will be executed when the project is executed and the button is clicked. We leverage the event handler method.

In figure 07 we add one line of code to the event handler. The code simply puts the message "Hello World" in the label that we put on the JFrame.

The setText( ) method is a member of the JLabel class.

Figure 07 - Add code to the Event Handler
Figure 07 - Add code to the Event Handler

The program is now ready to run. it doesn't do much, but it does illustrate the concept of event-driven programming in Java.

Figure 08 is the result of running the program and clicking on the button; the contents of the label is changed to "Hello World".

Figure 08 - The result of running the program and clicking the button
Figure 08 - The result of running the program and clicking the button

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      IntegrityYes 5 years ago

      I voted up for sure. That is informative.

    • Java Programs profile image

      Java Programs 6 years ago from India

      Great hub ..... will make so many willing programmer to learn a lot .... thanks

    • klanguedoc profile image

      Kevin Languedoc 6 years ago from Canada

      Great hub, good advice.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)