Java Video Tutorial 30

Java Swing TutorialYou asked for a giant tutorial that covers every Swing component, and in this tutorial I deliver. This is a big Java Swing Tutorial!

Here I create a complicated Java Swing layout. I set up everything in a GridBagLayout, but add a Box and  FlowLayout to it. I then show you how to use all of these components: JLabel, JTextField, JComboBox, JSpinner, JSlider, JRadioButton, ButtonGroup, JCheckBox, JTextArea, JScrollPane, ChangeListener, pack and more.

All of the code follows the video.

If you like videos like this share it

Code From the Video

import java.awt.*;

import javax.swing.*;
import javax.swing.event.*;

import java.util.Calendar;
import java.util.Date;


public class Lesson30 extends JFrame{
	
	JLabel nameLabel, streetLabel, stateLabel, dateLabel,
		ageLabel, sexLabel, optionsLabel, aboutLabel;
	JTextField nameText, streetText;
	JComboBox stateList;
	JSpinner dateSpin;
	JSlider ageSlider;
	JRadioButton maleRadio, femaleRadio;
	ButtonGroup sexGroup;
	JCheckBox morningCheck, afterNCheck, eveningCheck;
	JTextArea aboutYou;
	
	
	public static void main(String[] args){
		
		new Lesson30();
		
	}
	
	public Lesson30(){
		
		// Create the frame, position it and handle closing it
		
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("Random Layout");
				
		JPanel thePanel = new JPanel();
				
		thePanel.setLayout(new GridBagLayout());
		
		nameLabel = new JLabel("  Name:");
		
		addComp(thePanel, nameLabel, 0, 0, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
		
		nameText = new JTextField(30);
		
		addComp(thePanel, nameText, 1, 0, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
		
		streetLabel = new JLabel("  Street:");
		
		addComp(thePanel, streetLabel, 0, 1, 1, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
		
		streetText = new JTextField(30);
		
		addComp(thePanel, streetText, 1, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
		
		// Create a set of radio buttons and wrap them in a group
		
		Box sexBox = Box.createVerticalBox();
		maleRadio = new JRadioButton("Male");
		femaleRadio = new JRadioButton("Female");
		ButtonGroup sexGroup = new ButtonGroup();
		sexGroup.add(maleRadio);
		sexGroup.add(femaleRadio);
		sexBox.add(maleRadio);
		sexBox.add(femaleRadio);
		sexBox.setBorder(BorderFactory.createTitledBorder("Sex"));
		addComp(thePanel, sexBox, 3, 0, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
		
		// Create a flow layout panel and space components 10px apart
		
		JPanel statePanel = new JPanel();
		statePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0));
		
		stateLabel = new JLabel("State");
		
		statePanel.add(stateLabel);
		
		// Create a combo box that will hold the states
		
		String[] states = {"PA", "NY", "OH", "WV", "NJ"};
		
		stateList = new JComboBox(states);
		
		statePanel.add(stateList);
		
		dateLabel = new JLabel("Appointment Date");
		
		statePanel.add(dateLabel);
		
		// Get todays date
		
		Date todaysDate = new Date();
				
		// Create a date spinner & set default to today, no minimum, or max
		// Increment the days on button presses
		// Can also increment YEAR, MONTH, or DAY_OF_MONTH
				
		dateSpin = new JSpinner(new SpinnerDateModel(todaysDate, null, null,
				   Calendar.DAY_OF_MONTH));
				
		// DateEditor is an editor that handles displaying & editing the dates
				
		JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(dateSpin, "dd/MM/yy");
		dateSpin.setEditor(dateEditor);
				
		statePanel.add(dateSpin);
		
		ageLabel = new JLabel("Age: 50");
		
		statePanel.add(ageLabel);
		
		// Creates a slider with a min value of 1 thru 100
		// and an initial value of 1
				
		ageSlider = new JSlider(1, 99, 50);
		
		// 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
						
		ageSlider.addChangeListener(lForSlider);
		
		statePanel.add(ageSlider);
		
		addComp(thePanel, statePanel, 1, 2, 5, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
		
		// Create check boxs and assign them to a group
		
		JCheckBox morningCheck, afterNCheck, eveningCheck;
		
		Box optionBox = Box.createVerticalBox();
		morningCheck = new JCheckBox("Morning");
		afterNCheck = new JCheckBox("Afternoon");
		eveningCheck = new JCheckBox("Evening");
		
		optionBox.add(morningCheck);
		optionBox.add(afterNCheck);
		optionBox.add(eveningCheck);
		optionBox.setBorder(BorderFactory.createTitledBorder("Time of Day"));
		addComp(thePanel, optionBox, 1, 3, 2, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE);
		
		// Create a text area that is 6 columns high and 40 long
		
		aboutYou = new JTextArea(6, 40);
		
		// Set the default text for the text area
		
		aboutYou.setText("Tell us something about you");
		
		// If text doesn't fit on a line, jump to the next
		
		aboutYou.setLineWrap(true);
		
		// Makes sure that words stay intact if a line wrap occurs
		
		aboutYou.setWrapStyleWord(true);
		
		// Adds scroll bars to the text area ----------
		
		JScrollPane scrollbar1 = new JScrollPane(aboutYou, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
				
		// Other options: VERTICAL_SCROLLBAR_ALWAYS, VERTICAL_SCROLLBAR_NEVER
				
		addComp(thePanel, scrollbar1, 2, 3, 3, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
		
		this.add(thePanel);
		
		// Adjusts the size of the frame to best work for the components
		
		this.pack();
		
		this.setVisible(true);
		
		// Define if the user can resize the frame (true by default)
		this.setResizable(false);
		
	}
	
	// Sets the rules for a component destined for a GridBagLayout
	// and then adds it 
	
	private void addComp(JPanel thePanel, JComponent comp, int xPos, int yPos, int compWidth, int compHeight, int place, int stretch){
		
		GridBagConstraints gridConstraints = new GridBagConstraints();
		
		gridConstraints.gridx = xPos;
		gridConstraints.gridy = yPos;
		gridConstraints.gridwidth = compWidth;
		gridConstraints.gridheight = compHeight;
		gridConstraints.weightx = 100;
		gridConstraints.weighty = 100;
		gridConstraints.insets = new Insets(5,5,5,5);
		gridConstraints.anchor = place;
		gridConstraints.fill = stretch;
		
		thePanel.add(comp, gridConstraints);
		
	}
	
	// Implements ActionListener so it can react to events on components
	
	private class ListenForSlider implements ChangeListener{

	// Called when the spinner is changed
		public void stateChanged(ChangeEvent e) {
					
			// Check if the source of the event was the button
					
			if(e.getSource() == ageSlider){
				
				// Change the value for the label next to the spinner
						
				ageLabel.setText("Age: " + ageSlider.getValue() );
						
							
			}
					
		}
			
			
			
	}
	
}

25 Responses to “Java Video Tutorial 30”

  1. mr.roshik says:

    i am learning css from your tutorial, soon i will start java from here , but sometime i play ur latest video from youtube 🙂 cos i love it. take care

  2. Punit says:

    Helps me allot..
    thank you…

  3. Adil says:

    Can we not just use Netbeans – ie, drag and drop those swing components? Are they any different? I know little about java and wondering if using that is going to be qualified as bad/problematic code?

    Also, any comments on JavaFx 2.x – is that going to take over Swing?

    Would appreciate your insight.

  4. Spiro says:

    I’m a programmer for 20 years and really enjoying your videos… you’ve a really good knack for explaining things .. keep it up ..

  5. Borko says:

    Hi Derek. Thank you very much for your knowledge of java. For the comment from above i like to say that you were right, once you start coding the gui for a while it kinda grows on you :D. I have a suggestion or a favor to ask, and that is:can you make a tutorial or point me to some resources about creating rtf or pdf documents dynamically, specifically for printing. i have to make program that prints out invoices. i created a program that prints out the gui. but in java you cant put a background on a gui, so that idea is flushed.
    Thanks in advance
    All the Best

  6. David says:

    Derek! I’m getting there! Kids have had me take a break but I come right back! I really want to get certified in this by November!

    • Derek Banas says:

      Keep at it. I think I did a better job of explaining OOP in the first 2 videos in my Design Patterns Video Tutorial. Always feel free to ask questions.

      • David McMonigle says:

        I am getting super excited about this too(I’m both Dave and the name above).

        I’ve decided to design a baseball season tracker. I tried it before in Excel Using VBA, but I hit a snag when I wanted to chart the location of pitches. I realize now that I can draw the locations onto a panel within a panel within the main panel! Although I have an issue:

        how can I have the mouse listener draw a small circle where you double click it?

        • Derek Banas says:

          That sounds very cool! I actually show you how to make a paint app and how to store vector drawings or marks like you said starting in part 47 of my Java tutorial. I think what is taught in the next couple videos after that will be what you need.

          I hope that helps 🙂 – Derek

          • David McMonigle says:

            I am getting giddy just thinking about it! VBA was very frustrating, it was great for numbers and such, but I couldn’t do what I’m doing now with Java. All thanks to you good sir!

  7. Sam says:

    Derek would you be making any videos on Servlet & JSP.

    anytime?

    • Derek Banas says:

      I have been planning enterprise videos for a while. I have just been caught up making android tutorials and I want to cover them completely first. Sorry it is taking so long.

Leave a Reply

Your email address will not be published.

Google+