Source of HelloGUIApp6.java


  1: //HelloGUIApp6.java
  2: //Displays a message which changes and "marches" off the window
  3: //when a "Click Me" button is repeatedly pressed, as well as a
  4: //Quit button which closes the application.

  6: import java.awt.*;
  7: import java.awt.event.*;

  9: public class HelloGUIApp6
 10: extends Frame
 11: implements ActionListener
 12: {
 13:     private Button clickButton;
 14:     private Button quitButton;
 15:     private Hello hello;

 17:     public static void main(String[] args)
 18:     {
 19:         HelloGUIApp6 application = new HelloGUIApp6();
 20:         application.setSize(300, 300);
 21:         application.setVisible(true);
 22:     }


 25:     public HelloGUIApp6()
 26:     {
 27:         setTitle("Hello with Two Buttons");
 28:         setLayout(null);
 29:         setBackground(Color.yellow);

 31:         clickButton = new Button("Click Me");
 32:         clickButton.setLocation(20, 30);
 33:         clickButton.setSize(100, 100);
 34:         clickButton.setBackground(Color.green);
 35:         clickButton.addActionListener(this);
 36:         add(clickButton);

 38:         quitButton = new Button("Quit");
 39:         quitButton.setLocation(180, 30);
 40:         quitButton.setSize(100, 100);
 41:         quitButton.setBackground(Color.red);
 42:         quitButton.addActionListener(this);
 43:         add(quitButton);

 45:         hello = new Hello(120, 200, "Hello, world!");
 46:     }


 49:     public void actionPerformed(ActionEvent event)
 50:     {
 51:         if (event.getSource() == clickButton)
 52:         {
 53:             hello.reAdjust();
 54:             repaint(); //Try commenting out this line.
 55:         }
 56:         if (event.getSource() == quitButton)
 57:             System.exit(0);
 58:     }


 61:     public void paint(Graphics g)
 62:     {
 63:         hello.display(g);
 64:     }
 65: }


 68: class Hello
 69: {
 70:     private int xCoord;
 71:     private int yCoord;
 72:     private String msg;


 75:     public Hello(int initialX,
 76:                  int initialY,
 77:                  String initialMsg)
 78:     {
 79:         xCoord = initialX;
 80:         yCoord = initialY;
 81:         msg = initialMsg;
 82:     }


 85:     public void reAdjust()
 86:     {
 87:         xCoord += 10;
 88:         yCoord += 10;
 89:         msg = "Good-bye, cruel world!";
 90:     }


 93:     public void display(Graphics g)
 94:     {
 95:         g.drawString(msg, xCoord, yCoord);
 96:     }

 98: }