import java.awt.*; class Array extends Panel { private int size; // so many number buttons private Font plain, bold; // fonts for the number buttons public Array(int sizeOf) { super(); size = sizeOf; plain = new Font("Dialog", Font.PLAIN, 12); bold = new Font("Dialog", Font.BOLD, 12); // the number buttons are in a grid setLayout(new GridLayout(0, 10)); // make the number buttons for (int i = 1; i <= size; i++) { Button b = new Button(String.valueOf(i)); b.setFont(bold); add(b); } // "1" is not a prime, pre-disable it getComponent(0).disable(); getComponent(0).setFont(plain); } public boolean action(Event evt, Object what) { // get button label, supposedly a number int b; try { b = Integer.parseInt((String)what); } catch (NumberFormatException e) { return super.action(evt, what); } // sift Component c; for (int i = b+b; i <= size; i += b) { c = getComponent(i-1); if (c.isEnabled()) { c.disable(); c.setFont(plain); } } return true; } } public class Sieve extends java.applet.Applet { private static final int defaultSize = 50; private int size = defaultSize; private Array array; // the number buttons private TextField sizeEntry; // user enters desired size here private Button commit; // start/re-start button public void init() { array = new Array(defaultSize); sizeEntry = new TextField( String.valueOf(defaultSize), 4 ); commit = new Button("Reset"); Panel top = new Panel(); // use this to contain sizeEntry and commit top.add(new Label("Size:", Label.RIGHT)); top.add(sizeEntry); top.add(commit); add(top); add(array); } public boolean action(Event e, Object arg) { if (e.target == commit) { // user pushes the button commit.disable(); // get user's new size int newSize; try { newSize = Integer.parseInt(sizeEntry.getText()); } catch (NumberFormatException ex) { return false; // in case user enters non-number, nevermind } // further check of newSize, like, it should be >= 2 if (newSize < 2) return false; // if not >= 2, nevermind remove(array); size = newSize; array = new Array(size); add(array); // assume it has been the last guy validate(); commit.enable(); return true; } return super.action(e, arg); } }