CPSC 124, Spring 2014
Sample Answers to Quiz #8

Question 1. What are the two basic ways that a JPanel can be used?

Answer. A JPanel can be used as a "container" that holds other components, or it can be used as a "drawing surface." (These two functions can be mixed, but most often a panel is used in only one of these ways.) To use a panel as a drawing surface, it is necessary to create a subclass of JPanel and override the paintComponent metnod in the subclass. For use as a container, there is no need to make a subclass; it is only necessary to add components to the panel and possibly specify its layout manager.

Question 2. Explain the function of a layout manager in Java?

Answer. A layout manager is an object that is responsible for laying out the components in a JPanel (or other container). That is, the layout manager sets the sizes and positions of the components that are added to the panel. A layout manager implements some policy about how to lay out the components. For example, a GridLayout arranges the components into rows and columns of equal-sized cells.

Question 3. Name two of Java's standard GUI components (other than JPanel), and briefly discuss the function of each component.

Answer. For example...

A JTextField is a component that allows the user to enter one line of text. It appears on screen as an input box. The user can click the box to give it focus and then type into the box. The program can retrieve the user's input by calling the JTextField's getText() method.

A JLabel is a simple component that displays some text to the user. The program can change the text that is displayed by calling the JLabel's setText() method.

A JButton is a simple button that the user can click to cause some action to be taken by the program. The program can respond to the click by adding an ActionListener to the button. The ActionListener will be notified when the button is clicked and can take the appropriate action.