// for loop, parseInt, % mod, methods
import java.awt.*;
import java.awt.event.*;
public class Factors extends Frame implements ActionListener
{
public static void main(String[] args) // main starts the program
{
new Factors(); // construct a copy of Factors class
}
//--- Create Controls - Buttons, TextFields, etc ---
Label max = new Label("Max Num");
TextField last = new TextField("100",8);
Button calc = new Button("Calculate Factors");
List nums = new List(10); // List has 10 rows
Button quit = new Button("Exit Program");
//--- Constructor - add components to Frame -------
public Factors()
{
super("Factors"); // run Frame constructor and set Title
setSize(200,300); // Set size of window
setLayout(new FlowLayout()); // Use FlowLayout - the simplest Layout
add(max); // Place controls into Frame
add(last); // they are added in order and
add(calc); // placed one after another
add(nums); // as they fit
add(quit);
calc.addActionListener(this); // Handle button actions with
quit.addActionListener(this); // actionPerformed method in this object
last.addActionListener(this); // Responds to [Enter] key in TextField
setVisible(true); // remember to make Frame visible
}
//--- Responds to Buttons and TextField actions ----
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource(); // find out which button was clicked
if (source == quit)
{ System.exit(0); } // ends the program
else if ((source == calc) || (source == last))
{ findFactors(); } // call findFactors method
}
//--- a method for doing the calculations ----------
public void findFactors()
{
calc.setBackground(Color.red); // red Button indicates busy
String s = last.getText(); // get String from last TextField
int number = Integer.parseInt(s); // change String s to an int number
nums.removeAll(); // clear nums List
for (int fac=2; fac <= number; fac = fac+1 ) // count from 2 to number
{
if (number % fac == 0) // if factor then add to list
{ nums.add( fac + ""); } // fac + "" converts number to String
}
calc.setBackground(Color.green); // finished
}
}
|