Java Video Tutorial 23

Java Swing TutorialToday I complete the Java Swing tutorial I started in part 22 of the Java tutorial.

I implement the Swing event listeners. I then cover how to format numbers in Java so that they have commas or are displayed as currency. JOptionPane, a useful popup window in Java is introduced. And, finally I review much of what we have done in past Java Swing Tutorials.

All of the code follows the video. You should look at it to help you learn.

If you like videos like this share it

Code From the Video

import javax.swing.*;

import java.awt.event.*;

// New event listener that monitors changing values for components

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

// Allows me to format the numbers

import java.text.NumberFormat;

// Allows me to edit borders on panels

import javax.swing.border.*;

public class Lesson22 extends JFrame{
	JButton button1;
	JLabel label1, label2, label3;
	JTextField textField1, textField2;
	JCheckBox dollarSign, commaSeparator;
	JRadioButton addNums, subtractNums, multNums, divideNums;
	JSlider howManyTimes;
	double number1, number2, totalCalc;
	public static void main(String[] args){
		new Lesson22();
	public Lesson22(){
		// Define the size of the frame
		this.setSize(400, 400);
		// Opens the frame in the middle of the screen
		// Define how the frame exits (Click the Close Button)
		// Define the title for the frame
		this.setTitle("My Third Frame");
		// The JPanel contains all of the components for your frame
		JPanel thePanel = new JPanel();
		// ---------------------------------------------------------
		// Create a button with Click Here on it
		button1 = new JButton("Calculate");
		// Create an instance of ListenForEvents to handle events
		ListenForButton lForButton = new ListenForButton();
		// Tell Java that you want to be alerted when an event
		// occurs on the button
		// How to add a label --------------------------
		label1 = new JLabel("Number 1");
		// How to add a text field ----------------------
		textField1 = new JTextField("", 5);
		// How to add a label --------------------------
		label2 = new JLabel("Number 2");
		// How to add a text field ----------------------
		textField2 = new JTextField("", 5);
		// How to add checkboxes ------------------------
		dollarSign = new JCheckBox("Dollars"); 
		commaSeparator = new JCheckBox("Commas");
		// By putting true in here it is selected by default
		thePanel.add(commaSeparator, true);

		// Creates radio buttons with default labels
		addNums = new JRadioButton("Add");
		subtractNums = new JRadioButton("Subtract");
		multNums = new JRadioButton("Multiply");
		divideNums = new JRadioButton("Divide");
		// Creates a group that will contain radio buttons
		// You do this so that when 1 is selected the others
		// are deselected
		ButtonGroup operation = new ButtonGroup();
		// Add radio buttons to the group
		// Create a new panel to hold radio buttons
		JPanel operPanel = new JPanel();
		// Surround radio button panel with a border
		// You can define different types of borders
		// createEtchedBorder, createLineBorder, createTitledBorder
		// createLoweredBevelBorder, createRaisedBevelBorder
		Border operBorder = BorderFactory.createTitledBorder("Operation");
		// Set the border for the panel
		// Add the radio buttons to the panel
		// Selects the add radio button by default
		// Add the panel to the main panel
		// You don't add the group
		// How to create a slider ----------------
		label3 = new JLabel("Perform How Many Times?");
		// Creates a slider with a min value of 0 thru 99
		// and an initial value of 1
		howManyTimes = new JSlider(0, 99, 1);
		// Defines the minimum space between ticks
		// Defines the minimum space between major ticks
		// Says to draw the ticks on the slider
		// Says to draw the tick labels on the slider
		// Create an instance of ListenForEvents to handle events
		ListenForSlider lForSlider = new ListenForSlider();
		// Tell Java that you want to be alerted when an event
		// occurs on the slider
		// Gives focus to the textfield
	private class ListenForButton implements ActionListener{
		// This method is called when an event occurs
		public void actionPerformed(ActionEvent e){
			// Check if the source of the event was the button
			if(e.getSource() == button1){
				// getText returns a String so you have to parse it
				// into a double in this situation
					number1 = Double.parseDouble(textField1.getText());
					number2 = Double.parseDouble(textField2.getText());
				catch(NumberFormatException excep){
					// JOptionPane displays a popup on the screen
					// (parentComponent, message, title, error icon)
					JOptionPane.showMessageDialog(Lesson22.this, "Please Enter the Right Info", "Error", JOptionPane.ERROR_MESSAGE);
					System.exit(0); // Closes the Java app
				if(addNums.isSelected()) { totalCalc = addNumbers(number1, number2, howManyTimes.getValue()); 
				} else if(subtractNums.isSelected()) { totalCalc = subtractNumbers(number1, number2, howManyTimes.getValue()); 

				} else if(multNums.isSelected()) { totalCalc = multiplyNumbers(number1, number2, howManyTimes.getValue()); 
				} else { totalCalc = divideNumbers(number1, number2, howManyTimes.getValue()); }
				// If the dollar is selected in the checkbox print the number as currency
				if(dollarSign.isSelected()) {
					// Defines that you want to format a number with $ and commas
					NumberFormat numFormat = NumberFormat.getCurrencyInstance();
					JOptionPane.showMessageDialog(Lesson22.this, numFormat.format(totalCalc), "Solution", JOptionPane.INFORMATION_MESSAGE);
				// If the comma is selected in the checkbox print the number with commas
				else if(commaSeparator.isSelected()) {
					// Defines that you want to format a number with commas
					NumberFormat numFormat = NumberFormat.getNumberInstance();
					JOptionPane.showMessageDialog(Lesson22.this, numFormat.format(totalCalc), "Solution", JOptionPane.INFORMATION_MESSAGE);
				} else {
				JOptionPane.showMessageDialog(Lesson22.this, totalCalc, "Solution", JOptionPane.INFORMATION_MESSAGE);
	// Implements ActionListener so it can react to events on components
		private class ListenForSlider implements ChangeListener{

			public void stateChanged(ChangeEvent e) {
				// Check if the source of the event was the button
				if(e.getSource() == howManyTimes){
					label3.setText("Perform How Many Times? " + howManyTimes.getValue() );
		public static double addNumbers(double number1, double number2, int howMany){
			double total = 0;
			int i = 1;
			while(i <= howMany){
				total = total + (number1 + number2);
			return total;
		public static double subtractNumbers(double number1, double number2, int howMany){
			double total = 0;
			int i = 1;
			while(i <= howMany){
				total = total + (number1 - number2);
			return total;
		public static double multiplyNumbers(double number1, double number2, int howMany){
			double total = 0;
			int i = 1;
			while(i <= howMany){
				total = total + (number1 * number2);
			return total;
		public static double divideNumbers(double number1, double number2, int howMany){
			double total = 0;
			int i = 1;
			while(i <= howMany){
				total = total + (number1 / number2);
			return total;

28 Responses to “Java Video Tutorial 23”

  1. I use internet in a daily basis for over 12 years, and I must admit that today, I had a weird feeling! The information you provide throught your articles and videos is enormously valuable and mind-blowing, so that I want to send you 1000 dollars, just to thank you. Of course I am not rich, but I must say that this feeling is so new to me. Keep up the good work, I need more time to go deep in the knowledge which so kindly (and free) you provide to us. Keep up the good work!
    A Salut from a “poor” greek developer 🙂

    • admin says:

      Thank you 🙂 It makes me very happy that you enjoy the site. Don’t ever feel obligated to donate anything. I don’t do this for money. If I did I’d cover all of my videos with pre-roll ads on YouTube.

      Sites like mine aren’t supposed to work. You’re not supposed to cover numerous topics. I’m so happy that I have the freedom to cover programming, psychology, cooking, or whatever random thing I’m interested in. I’ll soon start covering electronics, chemistry and microbiology.

      It’s a fun hobby. I’m glad other people find use in it. I’m also very happy that people all over the world seem to like it. I’m actually more popular in numerous other countries well beyond my popularity in the US.

      Thanks for taking the time to show your appreciation


      • Obdulio Cristales says:

        Your java tutorial videos are excellent, best I’ve seen on the net.
        Do you know where I can find similar tutorial for C#.

        Thank you Derek

        • admin says:

          Thank you very much. I’m glad you like them. I’m sorry, but I can’t make C# tutorials because I don’t have a PC with screencast software. C# only works on PCs and not Macs, or Linux machines. I’ve seen a bunch of C# presentations on YouTube. I’m sure you will find one there that will work. I don’t know of anyone that makes heavily edited tutorials like I do, so I can’t really recommend anyone like me. Thank you for taking the time to say Hi 🙂

  2. Anonymous says:

    hii i have a question, you type one line in this code:
    JOptionPane.showMessageDialog(Practice_22.this, “Please enter the right info”, “Error”, JOptionPane.ERROR_MESSAGE);

    what is the mean of this, and why you used it here??

    • admin says:

      JOptionPane.showMessageDialog() is the method that opens the popup on the screen. It’s what pops up on the screen when I click on the button

  3. Sankar says:

    Great Videos; Rich in content. The best ever video tutorials till date I found on this amazingly connected world.

    Thanks for the videos. Videos helped me a lot.

    Again, I am thankful to you from the bottom of my heart ..!

  4. Matt says:

    Hey again Derek (my username on here was SilentSonance), at this point in your series I decided to try and make something of my own, so I tried to create a currency converter. Everything works pretty well with it except it always executes the catch-block in the KeyListener class. I want it to update the converted amount dynamically, that’s why I have it set up the way I do. It runs just fine after the first key is pressed and the JOptionPane window is gone. If you get a chance, could you look over the source code real quick?

    Thank you again (I’m SilentSonance on YouTube) so much for all these tutorials, I feel like I’m learning a ton.

  5. med says:

    Hi again. Two issues I’m having with this tutorial:

    in the action listener if statement right after the catch, netbeans says that it’s expecting two doubles not two doubles and the ‘howMany’ int.

    int the addNumbers, subtractNumbers etc methods I’m getting errors but I think it’s the same problem… Netbeans wants another parenthesis where it shouldn’t. It also no longer likes the return statement saying its not necessary.

    I have double checked the code but cannot see an error. If this isn’t enough info I’ll paste it in.

    If you have the time I’d be grateful for the help.

  6. Med says:

    lol… I checked it again!! not even going to admit to the error that I found.. Sorry for bothering you!!

  7. David says:

    I hit a snag with the Regular Expressions, but picked it back up with Swing. Can’t wait to work on some text based games later on!

  8. cg says:

    at line 253 and elsewhere, i notice that NumberFormat never uses the “new” keyword. why is that? i thought “new” was used whenever you were not dealing with a primitive variable. i tried it with “new” and got an error : )
    thanks for your very excellent work derek.

  9. Laurence Quinn says:

    I can never thank you enough. It is something I have to deal with everyday but programming is not taught very well in a lot of universities, mine in that category. But the video and audio combination is just perfect. The speed, the tone, the content are all perfect Derek. It’s just what I and millions of other people need and you are the man to give it to us!

    Thank you!

    • Derek Banas says:

      Thank you very much for taking the time to tell me that I help 🙂 I very much appreciate that. I will continue making tutorials for as long as possible and they will always be free.

  10. James says:

    Hey, first off I want to say that you are doing a great job. There is something that I feel will help out everyone though. I feel that you should teach proper formatting and organization of code. Getting people used to grouping certain objects is going to help them so much in the long run. I am following you tutorials but just using my own organization. In the long run it will help people write better code and it is easier to edit the program if need be. Once again great work on these tuts, sorry if this comment doesn’t really matter because the video is over a year old. Just thought I would put my time in to give you some feedback for all the time you put in for us 😀 Thanks!

  11. kelvin says:

    wow the best video tutorial i have seen in ages i am new to java and i actually have done away with books your explaining makes it pretty easy to understand and it makes learning fun

  12. sam says:

    I finally managed to fix it and do what you did, but i get a .jar file not a .exe file, so windows users will have to right click select open with java SE binary – a real pain.

  13. sam says:

    I fixed it thanks for your amazing videos they are incredibly helpful.

    p.s. im gonna get a brain aneurysm soon from too much thinking

Leave a Reply

Your email address will not be published.