cs205: engineering software? |
(none) 05 April 2010 |
public void addActionListener(ActionListener l) MODIFIES: this EFFECTS: Adds an ActionListener l to the button. public void setEnabled(boolean b) MODIFIES: this EFFECTS: If b, enables this. Otherwise, disables this.Why are inner classes useful for GUI programming?
Anonymous Inner Classes:
var = new Superclass () { // override methods here }Why does it only make sense to override methods (and not introduce new methods) in an anonymous inner class definition?
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GUI { private static void showGUI() { JFrame frame = new JFrame("Swing GUI"); java.awt.Container content = frame.getContentPane(); content.setLayout(new FlowLayout()); final JButton onButton = new JButton ("On"); final JButton offButton = new JButton ("Off"); ActionListener bl = new ActionListener (){ public void actionPerformed (ActionEvent e) { if (e.getActionCommand().equals ("On")) { onButton.setEnabled(false); offButton.setEnabled(true); } else if (e.getActionCommand().equals("Off")) { onButton.setEnabled(true); offButton.setEnabled(false); } } }; onButton.addActionListener(bl); offButton.addActionListener(bl); offButton.setEnabled(false); content.add(onButton); content.add(offButton); frame.pack(); frame.setVisible(true); } public static void main(String args[]) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); } }); } }