Introduction to Java  
 
 

Week 8

Readings:

  • Chapter 14.6-8

Lesson Outline:

  • JRadioButton, JComboBox, JList
  • Menus
  • Mouse events

Lesson Goals:

  • Learn how to construct JRadioButtons, JComboBoxes, and JLists
  • Create Menus in a menu bar
  • Understand implementing mouse events

Additional Reading:

Now that you have an understanding of the simpler GUI components, we will be moving on to the more complex ones. We will start with the JRadioButton. This is something similar to check boxes, which can be selected or deselected, but only allowed one button to be selected at a time. It creates both action and item events to be used in your coding. Let's try out this as an example.

Exercises:

  • Create a small JFrame that contains a four possibility radio button, and an Ok button. The four possibilities should be Java, C++, C, and Python. When you select one of the radio buttons and press ok, the title of the frame should change to "I enjoy coding in " followed by the selected language.
Now let's try out the JComboBox. This is a component that allows you to select between various options from a dropdown menu.
  • For this exercise, I want you to modify the code you have above to function the same way, but with a JComboBox instead of a JRadioButton.
Then there is the JList. This is very useful when you need to display long lists of items, and it also allows for multiple selections in certain circumstances.
  • Create a JFrame with one JList, which uses the JScrollPane class to allow for scroll bars on the side, and one JButton called ok. Fill the one list with words and set the action listener to print out the selected word.
Now let's move on to menus. The construction of menus is actually a multi-step process. The menus are constructed by first making and attaching a JMenuBar object to a JFrame. Then a JMenu object is created. You then create all the JMenuItem objects that you wish and add them to the JMenu object. The JMenu object is then attached to the JMenuBar.
  • In this exercise, you will create a GUI which contains at least two Menus in a menu bar with multiple options inside of each. You will also have a JLabel with text which will be altered depending up which menu item has been selected. The text can be whatever you wish.
The final advanced GUI component we will be covering is mouse events. This is the creation of mouse listeners which detect where the mouse is and when you click on it. For this to work, the JFrame must implement the MouseListener class. All of it abstract methods accept MouseEvents as an argument.
  • Create a JFrame which implements the mouse listener. Using the mouseClicked method, print out to the terminal the x and y coordinates of every click in the JFrame. Also give the mousePressed() and mouseReleased methods something to print out as well.

Files to Be Downloaded