I've been testing my JApplets and they have been working fine. I discovered the Applet menu that always loads and I wanted to test out its menu items. When I tried the Restart menu item, I realized components such as JButton, JLabel, JTextBox were duplicating themselves and text that was set by an ActionEvent did not reset. Here is a sample JApplet:
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
public class ExampleJApplet extends JApplet implements ActionListener
{
private JLabel label= new JLabel();
public void init()
{
setLayout(new FlowLayout());
JButton button = new JButton("Press");
add(button);
add(label);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
label.setText("The button was pressed");
}
}
It works, but when I go to Applet - Restart, the JButton duplicates itself and the JLabel does not reset. I thought that init() was called only once, but with Restart, it is called more than once. So that my JApplets don't do this on Restart, should I declare and add components (not referred by other methods such as actionPerformed()) in a constructor or should I declare all components at class scope so they aren't treated as new Objects? Should instantiations be done in init() so that updated text is replaced by initialized text?