Source of Oracle.java


  1: import javax.swing.JApplet;
  2: import javax.swing.JButton;
  3: import javax.swing.JLabel;
  4: import javax.swing.JTextArea;
  5: import java.awt.Container;
  6: import java.awt.FlowLayout;
  7: import java.awt.event.ActionEvent;
  8: import java.awt.event.ActionListener;
  9: 
 10: public class Oracle extends JApplet implements ActionListener
 11: {
 12:     public static int LINES = 5;
 13:     public static int CHAR_PER_LINE = 40;
 14: 
 15:     private JTextArea theText;
 16:     private String question;
 17:     private String answer;
 18:     private String advice;
 19: 
 20:     public void init()
 21:     {
 22:         Container contentPane = getContentPane( );
 23:         contentPane.setLayout(new FlowLayout( ));
 24: 
 25:         JLabel instructions =
 26:             new JLabel("I will answer any question, " +
 27:                        "but may need some advice from you.");
 28:         contentPane.add(instructions);
 29: 
 30:         JButton getAnswerButton = new JButton("Get Answer");
 31:         getAnswerButton.addActionListener(this);
 32:         contentPane.add(getAnswerButton);
 33: 
 34:         JButton sendAdviceButton = new JButton("Send Advice");
 35:         sendAdviceButton.addActionListener(this);
 36:         contentPane.add(sendAdviceButton);
 37: 
 38:         JButton resetButton = new JButton("Reset");
 39:         resetButton.addActionListener(this);
 40:         contentPane.add(resetButton);
 41: 
 42:         theText = new JTextArea(LINES, CHAR_PER_LINE);
 43:         theText.setText("Questions and advice go here.");
 44:         contentPane.add(theText);
 45: 
 46:         answer = 
 47:             "The answer is: Look around."; //first answer
 48:     }
 49: 
 50:     public void actionPerformed(ActionEvent e)
 51:     {
 52:         String actionCommand = e.getActionCommand( );
 53:         if (actionCommand.equals("Get Answer"))
 54:         {
 55:             question = theText.getText();
 56:             theText.setText("That is a difficult question.\n" +
 57:                             "Please give me some advice\n" +
 58:                             "and click the Send Advice button.");
 59:                 }
 60:         else if (actionCommand.equals("Send Advice"))
 61:         {
 62:             advice = theText.getText();
 63:             theText.setText("That advice helped.\n" +
 64:                          "You asked the question: " + question +
 65:                          "\n" + answer +
 66:                          "\nClick the Reset button and" +
 67:                          "\nleave the program on for others.");
 68:             answer = "The answer is: " + advice;
 69:         }
 70:         else if (actionCommand.equals("Reset"))
 71:         {
 72:             theText.setText("Questions and advice go here.");
 73:         }
 74:         else
 75:             theText.setText("Error");
 76:      }
 77: }
 78: