September 22, 2003
Creating GUI widgets and using them
/* A simple first GUI applet that shows how to create active GUI widgets and use them using event-driven programming */
import java.awt.*; import java.applet.Applet; import java.awt.event.*;
public class FirstGUI extends Applet implements ActionListener, AdjustmentListener { Button pressMe, meToo; // there are two buttons Scrollbar bar; // and a scrollbar int barValue = 0; // this is the value of the scrollbar int pressCount = 0; // number of times the buttons were pressed public void init() { // Create a button widget pressMe = new Button("PressMe"); // Add it for display in the applet this.add(pressMe); // Register this applet as the button's lietener pressMe.addActionListener(this); // Second Button // Create a button widget meToo = new Button("Me Too!"); // Add it for display in the applet this.add(meToo); // Register this applet as the button's lietener meToo.addActionListener(this); // Add a scrollbar // create the gui widget for scroll bar bar = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 100); // add it to the applet this.add(bar); // register a listener for it bar.addAdjustmentListener(this); } // init public void paint(Graphics g) { g.drawString("Times pressed = " + pressCount, 30, 130); g.drawString("Slider value = " + barValue, 30, 150); } // paint public void actionPerformed(ActionEvent e) { // Whe a button is pressed, this is where you have control System.out.println("Button was pressed."); pressCount = pressCount + 1; repaint(); } // actionPerformed
public void adjustmentValueChanged(AdjustmentEvent e) { System.out.println("Slider moved..."); barValue = bar.getValue(); repaint(); } // adjustmentValueChanged } // FirstGUI