package HandGUI; import java.awt.*; // older GUI library, has layout stuff for components import java.awt.event.*; // events import javax.swing.*; // swing is a library of GUI components // example GUI // class extends JFrame, so it is its own window public class BunnyGUI extends JFrame { // the bunny private Bunny mrBun; // input private JButton feedbutton; // output private JLabel display; // constructor does all setup of window and buttons public BunnyGUI() { // set up the window super("Your pet bunny"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); // make Bunny that shows messages to user with JOptionPanes mrBun = new Bunny(); mrBun.setGooey(true); // my Bunny class knows it might talk to a GUI // output text box display = new JLabel(); // call our own method for updating the display updateDisplayBox(); // this is my method I made, not part of Java // button to feed the bunny feedbutton = new JButton("feed the bunny"); // give it an actionListener that calls a method feedbutton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { bunnyFeed(); // call method from outer class } } ); // put the widgets in the window add(new JLabel("BUNNY ENRICHMENT:")); // only makes sense if I will never change this label // otherwise label should live in an instance variable add(feedbutton); add(display); // make the window visible pack(); setVisible(true); } // feed the bunny // called by actionListener public void bunnyFeed() { // this also causes output by the bunny... it is annoying mrBun.feed((int) (Math.random() * 5) + 1); updateDisplayBox(); } // need to update display in several places, so stick it in its own method public void updateDisplayBox() { display.setText(mrBun.getName() + " ate " + mrBun.getCarrotCount() + " carrots total."); // since this can change the width, re-pack to resize the window pack(); } // main to launch the GUI public static void main(String[] args) { JOptionPane.showMessageDialog( null, // window to center over "Welcome to the Bunny Enrichment Center!", // output to show "Bunny Time!", // message box title JOptionPane.INFORMATION_MESSAGE); // message box style BunnyGUI gui = new BunnyGUI(); } }