TopEvent handlingMore Panels and GUI Components

More Panels and GUI Components

Now let's try to make our drawing program even better. It's inconvenient having to select a geometric type and then click in the window to create an object of that type. Why not just include buttons for the three kinds of objects.

The Swing class JButton represents buttons, and the constructor takes the button label as a parameter. JButton takes an ActionListener, just like JComboBox. Thus we must write:

    button.addActionListener(this);

while the class must implement ActionListener. The method associated with ActionListener is

    public void actionPerformed(ActionEvent evt) {...}

Unfortunately just adding three buttons to the bottom panel makes it so crowded that the four different items don't all show up. We can try to fix that by using the GridLayout to lay out the panel so that each item takes the same amount of space.

    bottomPanel.setLayout(new GridLayout(1,4));

Unfortunately that makes them too crowded so the labels of the buttons aren't readable. See BadButtonPanelDrawing.

A better solution is to add a separate panel to hold the three buttons and to place that panel above the slot for the color JComboBox. See ButtonPanelDrawing.


TopEvent handlingMore Panels and GUI Components