Java Reference
In-Depth Information
For action events, the event source is a button or other user-interface component,
or a timer. You need to add a listener object to each event source, like this:
ActionListener listener1 = new Button1Listener();
button1.addActionListener(listener1);
C OMMON E RROR 10.8: By Default, Components Have
Zero Width and Height
The sample GUI programs of this chapter display results in a label or text area.
Sometimes, you want to use a graphical component such as a chart. You add the
chart component to the panel:
panel.add(textField);
panel.add(button);
panel.add(chartComponent);
However, the default size for a component is 0 by 0 pixels, and the chart
component will not be visible. The remedy is to call the setPreferredSize
method, like this:
chartComponent.setPreferredSize(new
Dimension(CHART_WIDTH, CHART_HEIGHT));
GUI components such as buttons and text fields know how to compute their
preferred size, but you must set the preferred size of components on which you
paint.
P RODUCTIVITY H INT 10.2: Code Reuse
Suppose you are given the task of writing another graphical user-interface program
that reads input from a couple of text fields and displays the result of some
calculations in a label or text area. You don't have to start from scratch. Instead,
you canȌand often shouldȌreuse the outline of an existing program, such as the
foregoing InvestmentFrame class.
To reuse program code, simply make a copy of a program file and give the copy a
new name. For example, you may want to copy InvestmentFrame.java to a
file TaxReturnFrame.java . Then remove the code that is clearly specific to
Search WWH ::




Custom Search