// ArrayOfGUIComponents.java // Using an array to computer sales commission // Cooler version of ArrayOneDimension3 // Uses arrays of JLabels and JTextfields // APPLET CODE="ArrayOfGUIComponents" HEIGHT=400 WIDTH=100 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ArrayOfGUIComponents extends JApplet implements ActionListener { // GUI components Container c; JLabel months[ ]; JLabel commLabel; JTextField tfSales[ ]; JTextField outputComm; JButton compute; int sales[ ]; // array of monthly sales data double rate1, rate2; // rate1 is applied to first 100 and rate2 to any excess int comm; public void init( ) { sales = new int[ 6 ]; rate1 = .1; rate2 = .2; // GUI components c = getContentPane( ); c.setLayout( new FlowLayout( ) ); months = new JLabel[ 6 ]; // creates the array of labels commLabel = new JLabel( "Commission" ); tfSales = new JTextField[ 6 ]; // creates the array of textfields outputComm = new JTextField( 8 ); outputComm.setEditable( false ); compute = new JButton( "COMPUTE" ); compute.addActionListener( this ); for ( int i = 0; i < months.length; i++ ) { months[ i ] = new JLabel( "Month " + ( 1 + i ) ); // creates each individual label c.add( months[ i ] ); tfSales[ i ] = new JTextField( 5 ); // creates each individual textfield c.add( tfSales[ i ] ); } c.add( commLabel ); c.add( outputComm ); c.add( compute ); } public void actionPerformed( ActionEvent e ) { // initialize comm comm = 0; // get the sales data and fill sales array for ( int i = 0; i < months.length; i++ ) sales[ i ] = Integer.parseInt( tfSales[ i ].getText( ) ); // compute the commission for ( int i = 0; i < sales.length; i++ ) comm += ( rate1 * Math.min( sales[ i ], 100 ) + rate2 * Math.max( 0, sales[ i ] - 100 ) ); outputComm.setText( String.valueOf( comm ) ); } }