/* Copyright Derek Park 2001 * All Rights Reserved * * For terms of use: * http://www.gelaed.com */ import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.BoxLayout; import javax.swing.Box; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * A class to demonstrate the very basics of applet implementatiom */ public class ButtonJApplet extends JApplet implements ActionListener { // declare two buttons to instantiate later JButton button1, button2; /** * init() must be in every applet that is expected to run * init() is similar to the main() method in an * executable (non-applet) class */ public void init() { // change the background to white instead of the default getContentPane().setBackground(Color.white); // create and use a BoxLayout so the buttons and labels are // displayed in the desired order // without a LayoutManager such as BoxLayout, the contentPane // will only display the last Component (e.g. JButton) // added, and it will fill the Container fully getContentPane().setLayout( new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); // create boxes to hold the buttons and labels, // so we can format better Box button1Box = new Box(BoxLayout.Y_AXIS); Box button2Box = new Box(BoxLayout.Y_AXIS); // add the first box to the contentPane getContentPane().add(button1Box); // add a 20 pixel spacer between the two boxes getContentPane().add(Box.createHorizontalStrut(20)); // add the second box getContentPane().add(button2Box); // create new buttons button1 = new JButton("Disable Button 2"); button2 = new JButton("Disable Button 1"); // add ActionListeners to our buttons so we can "hear" when // they are clicked button1.addActionListener(this); button2.addActionListener(this); // create new labels JLabel button1Label = new JLabel("Button 1:"); JLabel button2Label = new JLabel("Button 2:"); button1Label.setLabelFor(button1); button2Label.setLabelFor(button2); // add the labels that we've created button1Box.add(button1Label); button1Box.add(button1); button2Box.add(button2Label); button2Box.add(button2); } /** * We Must have an actionPerformed method to find out when a * button has been clicked */ public void actionPerformed(ActionEvent e) { // we need to check to see what action was performed if (e.getActionCommand() == "Disable Button 2") { button2.setEnabled(false); button1.setText("Enable Button 2"); } else if (e.getActionCommand() == "Disable Button 1") { button1.setEnabled(false); button2.setText("Enable Button 1"); }else if (e.getActionCommand() == "Enable Button 2") { button2.setEnabled(true); button1.setText("Disable Button 2"); } else if (e.getActionCommand() == "Enable Button 1") { button1.setEnabled(true); button2.setText("Disable Button 1"); } } }