Event handlingTopSwing

Swing

As indicated in the textbook, adding graphic user interface (GUI) items to the screen is pretty easy. Here are the steps:

  1. Create the item and initialize it if necessary. E.g.,
    		figureMenu = new JComboBox();
    		figureMenu.addItem("FramedSquare");
    		figureMenu.addItem("FramedCircle");
    		figureMenu.addItem("FilledSquare");
    
  2. Add the items to the content pane of the WindowController, and validate the pane. E.g.,
    		Container contentPane = getContentPane();
    		contentPane.add(figureMenu, BorderLayout.SOUTH);
    		contentPane.add(colorMenu, BorderLayout.NORTH);
    		contentPane.validate();
    

In Java 5 you may add the components directly to the WindowController rather than first getting the content pane and adding to it. Thus in Java 5 you can write:

    this.add(figureMenu, BorderLayout.SOUTH);
    this.add(colorMenu, BorderLayout.NORTH);
    this.validate();

or even omit the this altogether.

A simple example of this is the program ComboBoxDrawing. In this program, if you click anywhere in the drawing area, a geometric figure will be drawn in the middle of the screen. The figure to be drawn is dependent on the setting of the figureMenu. The item selected on the menu is obtained by evaluating figureMenu.getSelectedItem().


Event handlingTopSwing