Creating GUIs With Java Swing

Transcription

CISC 275: Introduction to Software EngineeringLab 3:Creating GUIs with Java SwingCharlie GreenbackerUniversity of DelawareFall 20111

Overviewl Java Swing at a glancel Simple “Hello World” examplel MVC reviewl Intermediate examplel Lab exercise2

Java Swing at a glancel Java toolkit for graphical user interfaces (GUIs)l Provides native “look & feel” based on host OSl More sophisticated than earlier AWT toolkitl Also supports customized “look & feel”l Lightweight; doesn't use host OS GUI APIl Makes for natural use of MVC pattern3

“Hello World” examplel l l We'll create a small window with just a single labelcontaining a “Hello World” message3 easy steps to get a GUI window on screen:l Set up the windowl Add a labell Show the windowAll of the following code lives inside a simple classwith just a main() method4

“Hello World” examplel Set up the window:l JFrame acts as window componentl Assign action to close button/operationJFrame frame new T ON CLOSE);5

“Hello World” examplel Add a label:l JLabel contains our messagel Add label to frame's content paneJLabel label new JLabel("Hello World!");frame.getContentPane().add(label);6

“Hello World” examplel Show the window:l Size frame to fit layout of components (pack)l Make frame visibleframe.pack();frame.setVisible(true);7

“Hello World” examplel l Run the program & you should see a window likethis (according to your OS of choice):Example code is available for review at:HelloWorldGUI.java8

MVC reviewl l l Model-View-Controller design patternIsolate data model from user interface fromapplication logicl Model: data model classesl View: user interface (i.e. GUI, console, etc.)l Controller: interacts w/ View, manipulates ModelNext example will demonstrate elements of MVC9

Intermediate examplel Uses part of MVC. the VC part, that isl l View is a window that extends JFrame classl l l l Really no “model” to speak ofCode looks a bit different than HelloWorldGUISelf-referencing; manipulates self (an extension ofJFrame) rather than a JFrame it createdController launches GUI & performs conversionExample program is a widget for converting fromCelsius to Fahrenheit temperatures10

Intermediate examplel Begin by defining the class & attributespublic class CelsiusConverterGUI extends JFrame {// variables used throughout classprivate static JLabel celsiusLabel;private static JButton convertButton;private static JLabel fahrenheitLabel;private static JTextField inputTextField;11

Intermediate examplel Initialize GUI window by adding componentsl Start by setting up the windowprivate void initComponents() {// set up the windowsetTitle("Celsius Converter");setDefaultCloseOperation(JFrame.EXIT ON CLOSE);setPreferredSize(new Dimension(250, 100));12

Intermediate examplel Initialize GUI window by adding componentsl Next, set up the individual componentsinputTextField new JTextField(10);celsiusLabel new JLabel("Celsius");convertButton new JButton("Convert");fahrenheitLabel new JLabel("Fahrenheit");13

Intermediate examplel Initialize GUI window by adding componentsl Then, initialize window layout & add componentssetLayout(new eitLabel);14

Intermediate examplel Initialize GUI window by adding componentsl Finally, create & assign action listener for buttonconvertButton.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent evt) {convertButtonActionPerformed(evt);}});} // end of initComponents() method15

Intermediate examplel Create & display Celsius conversion windowpublic CelsiusConverterGUI() {InitComponents();// the method we just made// show the windowpack();setVisible(true);}16

Intermediate examplel Implement event handler for button action listenerprivate voidconvertButtonActionPerformed(ActionEvent evt) {// parse Celsius value as Double, convert to// Fahrenheit, cast as intdouble tempFahr Double(inputTextField.getText()));// change text of Fahrenheit label to reflect// converted valuefahrenheitLabel.setText(tempFahr " Fahrenheit");}} // end of CelsiusConverterGUI class17

Intermediate examplel Controller class is extremely simplepublic class CelsiusController {public static void main(String[] args) {new CelsiusConverterGUI();}public static doublecelsiustofahrenheit(double celsius){return celsius * 1.8 32;}}18

Intermediate examplel l Run the program & you should see a window likethis (according to your OS of choice):Example code is available for review at:CelsiusConverterGUI.java & CelsiusController.java19

Lab Exercisel On your own or in pairs, add new functionality tothe Celsius Converterl l l l Add a drop-down list offering multiple conversionoptions (e.g., meters to inches, kgs to lbs) in GUIAdd new conversion methods to controllerProgram should make appropriate conversionbased on option selected in drop-down listEmail your code (GUI & controller files) tocharlieg@cis.udel.edu by Tuesday20

Lab Exercisel l Remember: you must follow MVC patternl No conversion code in GUI classl No GUI code in controller classYou will need to use some Java libraries and Swingfeatures not covered in these lab slidesl Consult the skeleton code for ideasl The Swing Tutorial from Sun is very helpfull Google is your friend, too21

Creating GUIs with Java Swing Charlie Greenbacker University of Delaware Fall 2011. 2 Overview! Java Swing at a glance! Simple “Hello World” example! MVC review! Intermediate example! Lab exercise. 3 Java Swing at a g