Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Perfect
extends JApplet
implements ActionListener {
JScrollPane jScrollPane1 = new JScrollPane();
JPanel ctrlPanel = new JPanel();
JButton ppnBtn = new JButton();
JTextArea reportTA = new JTextArea();
JButton clearBtn = new JButton();
public Perfect() {}
public void init() {
try {
jbInit();
// hook up buttons
this.ppnBtn.addActionListener(this);
this.clearBtn.addActionListener(this);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Print perfect numbers to textarea
*/
private void printPerfectNumbers() {
for (int i = 2; i <= 1000; i++) {
int sum = 0;
for (int j = 1; j < i; j++) {
if (i % j == 0) {
sum = sum + j;
}
}
if (sum == i) {
reportTA.append("" + i + " is a perfect number\n");
reportTA.append("Factors are: ");
for (int f = 1; f < i; f++) {
if (i % f == 0) {
reportTA.append(" " + f);
}
}
reportTA.append("\n");
}
}
}
/**
* Set up GUI
*/
private void jbInit() throws Exception {
ppnBtn.setText("Print Perfect Numbers");
reportTA.setText("");
clearBtn.setText("Clear");
this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
this.getContentPane().add(ctrlPanel, BorderLayout.SOUTH);
ctrlPanel.add(ppnBtn, null);
ctrlPanel.add(clearBtn, null);
jScrollPane1.getViewport().add(reportTA, null);
}
/**
* Handle button clicks
*/
public void actionPerformed(ActionEvent e) {
if (e.getSource() == ppnBtn) {
printPerfectNumbers();
}
else if (e.getSource() == clearBtn) {
reportTA.setText("");
}
}
/**
* MAIN for testing applet (uses the applet as a JPanel)
*/
public static void main(String[] args) {
JFrame f=new JFrame("Applet Test");
f.getContentPane().setLayout(new GridLayout());
Perfect applet=new Perfect();
f.getContentPane().add(applet);
applet.init();
f.setBounds(20,20,300,200);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}
Bookmarks