ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Programming in Java Netbeans - A Step by Step Tutorial for Beginners: Lesson 41

Updated on October 16, 2019
dwachira profile image

Danson Wachira is a certified Trainer in Computer Science, Information Technology and related studies.

Source

Lesson 41: Working with GUI controls: Radio buttons

In the previous lesson, we learnt how to work with Check box and Text area as Java Graphical User Interface (GUI) controls and we saw how we can select items using Check box and drop them into a Text area using some codes in a Command button. In this lesson, we shall continue with GUI controls in Java and discuss Radio buttons as GUI controls.

Radio buttons controls are used to select only one item from a list of many items. Unlike Check box, users cannot select multiple items through Radio buttons. This option of allowing users to select only one item from a list of items or options is very useful when the situation allow only one item to be selected, for instance, in the case of selecting Gender option.

For this lesson, you will need to create a new project and a new form as the one we have been using in previous lessons look filled already. Click on the File >> New Project. You can call the project a name of your choice but i have called it Radio Button here. Once you have created the project, go ahead and create a new Jframe form.

How to create a Jframe form
How to create a Jframe form

We’ll first start by labeling the form with a caption “Working with Radio Buttons” so, drag a label from the Swing Controls on the Palette window and drop it on the form. Apply the necessary font and foreground properties. I have made this to have font Calibri, size 24 and bold with a blue foreground color.

Radio buttons are better manipulated when they are on a panel, that way you can work with them as a group and it is easy to move them around on the form. From the Swing Containers on the Palette window, drag and drop a panel to the form and re-size appropriately.

Palette window
Palette window

From the Palette window under the Swing containers, locate for the Radio button control and drag it onto the panel. We want the user to select only one method of payment from the available options. Drop five radio button controls, changing caption text in each case. The text can be edited like we did with the Check boxes in the previous lesson. Let the variable name remain as the default name i.e. jRadioButton1

The final five radio buttons with all modes of payment labeled as radio buttons’ caption text should look as shown below when you run the form. Notice that we have applied some properties on font for radio button captions and also we have added a label at the top of radio buttons to let the user know what to do with the radio buttons.You can make these changes too.

One thing that you should have noticed when you run the form is that the radio buttons are not working as expected. We want the user to select only one method of payment but as of now we can select more than one option. See below:

To solve this and make the radio buttons to have a single selection only, we need to put the radio buttons in a Button Group. Button Group allows you to group radio buttons under one name where only one radio button can be selected at any given time.

To use Button Group, we need to import the Button Group class from the Swing library. Click on the source code section of the form and add the following import code just before the class code.

import javax.swing.ButtonGroup;

And then add the following method just after the class Constructor

private void groupButton( ) {

ButtonGroup bg1 = new ButtonGroup( );

bg1.add(jRadioButton1);
bg1.add(jRadioButton2);
bg1.add(jRadioButton3);

}

The groupButton() method above adds radio buttons to the ButtonGroup object through use of the add method. What we need next is to call the Button Group from the class Constructor because that way the radio buttons will be grouped when the form loads. The code segment now should look like shown below:

Run the form again and you should be able to select only one radio button now, selecting multiple radio buttons will not be possible. To get which radio button was selected, we are going to add a Command button on the form with the caption “Complete Payment Now.”

The command button will contain some codes with IF statements that will return the caption of the selected radio button through a JOptionPane message box. To get which radio button was selected, we’ll use the isSelected() method of the radio buttons.

The code in the command button should look as shown below, notice that we have added JOptionPane message box code at the end if the IF statements to output the text from the radio button that was selected.

Code in the command button ActionPerformed event

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String textradio = "";
    if(jRadioButton1.isSelected()){
        textradio = jRadioButton1.getText();
    }
    if(jRadioButton2.isSelected()){
        textradio = jRadioButton2.getText();
    }
    if(jRadioButton3.isSelected()){
        textradio = jRadioButton3.getText();
    }
    if(jRadioButton4.isSelected()){
        textradio = jRadioButton4.getText();
    }
    if(jRadioButton5.isSelected()){
        textradio = jRadioButton5.getText();
    }
   javax.swing.JOptionPane.showMessageDialog(this,"Pay with "+textradio+" ?");
}

Run the form now and you should be able to have a JOptionPane message box displaying the caption text of the selected radio button.

We are using the “this” keyword in the JOptionPane message box code to denote the object of the current form rather than using null which means no window. Radio buttons are some of the commonly used GUI controls in GUI programming. In the next lesson, we shall discuss Java Menus. See you then.

<< Lesson 40 | Lesson 42 >>

Comments

    0 of 8192 characters used
    Post Comment
    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi annitakison,

      I am glad that this tutorial was helpful, that motivates me to go on and on. Thanks for the visit and comment.

    • annitakison profile image

      Anni Takison 

      6 years ago from california, USA

      Wow.. You really provides us great and informative notes in java. My queries regarding radio button are now solved by the help your hub. Thanks. :)

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi Virma,

      If i offer something useful to beginners, then my mission is complete. Thanks for the visit and comment.

    • profile image

      Virma 

      6 years ago

      Awesome tutorial on Java programming, you have crafted this nicely and i know all Java beginners will love this, in fact i guess they are coming here in drones. Well done!!!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi kashmir56,

      Due to some commitments, i have not been updating this series but luckily today i had some strength to do it and hope i will pick myself again. Thanks for the visit and comment.

    • kashmir56 profile image

      Thomas Silvia 

      6 years ago from Massachusetts

      Another great hub in the series of programming in Java . Well done !

      Vote up and more !!!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi kidscrafts,

      I do understand your take here, coding can take a lot of ones time and sometimes a lot of "pain" locating those bugs, luckily you have a loving friend to take care of that. Thanks for the visit and comment.

    • kidscrafts profile image

      kidscrafts 

      6 years ago from Ottawa, Canada

      I used to be able to program those things when I took my multimedia course. Now, I am too busy working on the creative side of my website (add content) so my husband takes care of those aspects :-)))) Anyway...I am still working in multimedia because for my website, I use Photoshop, Flash (for animations), Cool Edit (for the sound), Avid Studio (for the video), Publisher (to create my documents) and occasionally Dreamweaver when I update the website of some of my clients. I think I have my hands full :-) No need to do radio buttons :-) But I am sure that with what you presented here so clearly, you will help a lot of people!

      Voted up and useful!

    • dwachira profile imageAUTHOR

      Danson Wachira 

      6 years ago from Nairobi, Kenya

      Hi Emman,

      Thanks for the visit and comment, keep reading as i will post more.

    • profile image

      Emman 

      6 years ago

      I don't know how you do it, but this is a useful tutorial worthy mentioning. May you continue to post more. Thanks.

    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)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)