/** * Name: Stuart Hansen * * Purpose: * This project illustrates how to open * and close a windowing application in Java * * Date: January 26, 2003 */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonsAndLabels extends JFrame { JButton helloButton; // sets the text to "Hello World!" JButton goodByeButton; // sets the text to "Good bye World!" JLabel messageLabel; // a label to display messages /** * Constructor for objects of class ClassWithButtonsAndLabels */ public ButtonsAndLabels() { // get the content pane and set the layout to null Container c = getContentPane(); c.setLayout(null); // Initialize the messageLabel messageLabel = new JLabel ("Are you coming or going?"); messageLabel.setSize(200, 30); messageLabel.setLocation (50, 50); c.add(messageLabel); // Add the hello button helloButton = new JButton("Hello"); helloButton.setSize(125, 30); helloButton.setLocation (50, 100); helloButton.addActionListener(new HelloHandler()); c.add(helloButton); // Add the good bye button goodByeButton = new JButton ("Good bye"); goodByeButton.setSize(125, 30); goodByeButton.setLocation(175, 100); goodByeButton.addActionListener(new GoodByeHandler()); c.add(goodByeButton); // Initialize the application window setTitle("Very Simple GUI"); setSize(500, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main (String [] args) { new ButtonsAndLabels(); } // An inner class to handle the hello button class HelloHandler implements ActionListener { public void actionPerformed (ActionEvent e) { messageLabel.setText("Hello World!"); } } // An inner class to handle the goodbye button class GoodByeHandler implements ActionListener { public void actionPerformed (ActionEvent e) { messageLabel.setText("Good bye Cruel World!"); } } }