public class UIDemo1 implements ActionListener { PRivate JFrame frame; private JButton button; private JTextArea area; private int index = -1; private String [] params;
private UIDemo1(String args[]) { params = args; area = new JTextArea(5,25); button = new JButton("Click here!"); button.addActionListener(this);
frame = new JFrame (getClass().getName()); frame.addWindowListener (new ReusableWindowAdapter()); Container cont = frame.getContentPane(); JScrollPane scrollPane = new JScrollPane(area); cont.add(scrollPane,BorderLayout.NORTH); cont.add(button,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); }
public void actionPerformed(ActionEvent ae) { //provide equality check to see if source was the //button defined above.. useful only if we register //this ActionListener with multiple sources if(ae.getSource().equals(button)) { index = ++index % params.length; area.setText(params[index]); } }
public static void main(String args[]) { if(args.length > 1) { UIDemo1 one = new UIDemo1(args); }else { usage(); } } private static void usage() { System.err.println ("You may excute this program as below:"); System.err.println ("java UIDemo1 params1 params2 ..."); System.exit(-1); } }
public class UIDemo2 { private JFrame frame; private JButton button; private JTextArea area; private int index = -1; private String [] params;
private UIDemo2(String args[]) { params = args; area = new JTextArea(5,25); button = new JButton("Click Here!"); button.addActionListener (new SemiReusableActionListener(this));
frame = new JFrame(getClass().getName()); frame.addWindowListener (new ReusableWindowAdapter()); Container cont = frame.getContentPane(); JScrollPane scrollPane = new JScrollPane(area); cont.add(scrollPane,BorderLayout.NORTH); cont.add(button,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } void setMessage(Object source) { if(source.equals(button)) { index = ++index % params.length; area.setText(params[index]); } }
public static void main(String args[]) { if(args.length > 1) { UIDemo2 two = new UIDemo2(args); }else{ usage(); } } private static void usage(){ System.err.println ("You may excute this program as below:"); System.err.println ("java UIDemo2 params1 params2 ..."); System.exit(-1); } }
//SemiReusableActionListener
import java.awt.event.*;
public class SemiReusableActionListener implements ActionListener { private UIDemo2 demo2; SemiReusableActionListener (UIDemo2 uiDemo) { demo2 = uiDemo; } public void actionPerformed (ActionEvent ae) { demo2.setMessage (ae.getSource()); } }