Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 91 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
91
Dung lượng
0,93 MB
Nội dung
548 CHAPTER 9 graphical user interfaces In the PickImage program, we set the list selection mode to single selection because only one image can be displayed at a time. However, even if multiple selections were allowed in this program, the getSelectedValue method returns the first item selected, so that would be the image displayed. A similar method called getSelectedValues returns an array of objects representing the items selected when multiple selections are permitted. Instead of an array of String objects, the JList constructor could be passed an array of ImageIcon objects instead. In that case, the images would be dis- played in the list. combo boxes A combo box allows the user to select one of several options. When the user presses a combo box using the mouse, a list of options is displayed from which the user can choose. The current choice is displayed in the combo box. A combo box is defined by the JComboBox class. Note the similarities and differences between a combo box and a JList object (described in the previous section). Both allow the user to select an item from a set of choices. However, the choices on a list are always displayed, with the current choice highlighted, whereas a combo box presents its options only when the user presses it with the mouse. The only item displayed all the time in a combo box is the current selection. A combo box can be either editable or uneditable. By default, a combo box is uneditable. Changing the value of an uneditable combo box can be accomplished only by selecting an item from the list. If the combo box is editable, however, the user can change the value by either selecting an item from the list or by typing a particular value into the combo box area. figure 9.11 List selection modes Single Selection Only one item can be selected at a time. Any combination of items can be selected. Multiple, contiguous items can be selected at a time. Single Interval Selection Multiple Interval Selection List Selection Mode Description A combo box provides a list of options from which to choose and displays the current selection. key concept 9.4 additional components 549 The options in a combo box list can be established in one of two ways. We can create an array of strings and pass it into the constructor of the JComboBox class. Alternatively, we can use the addItem method to add an item to the combo box after it has been created. Like a JList, a JComboBox can also display ImageIcon objects as options as well. The JukeBox program shown in Listing 9.14 demonstrates the use of a combo box. The user chooses a song to play using the combo box, and then presses the Play button to begin playing the song. The Stop button can be pressed at any time to stop the song. Selecting a new song while one is playing also stops the cur- rent song. The JukeBoxControls class shown in Listing 9.15 is a panel that contains the components that make up the jukebox GUI. The constructor of the class also loads the audio clips that will be played. An audio clip is obtained first by creat- ing a URL object that corresponds to the wav or au file that defines the clip. The first two parameters to the URL constructor should be “file” and “localhost” respectively, if the audio clip is stored on the same machine on which the program is executing. Creating URL objects can potentially throw an exception; therefore they are created in a try block. However, this program assumes the audio clips will be loaded successfully and therefore does nothing if an exception is thrown. Once created, the URL objects are used to create AudioClip objects using the static newAudioClip method of the JApplet class. The audio clips are stored in an array. The first entry in the array, at index 0, is set to null. This entry corre- sponds to the initial combo box option, which simply encourages the user to make a selection. The list of songs that are displayed in the combo box is defined in an array of strings. The first entry of the array will appear in the combo box by default and is often used to direct the user. We must take care that the rest of the program does not try to use that option as a valid song. The play and stop buttons are displayed with both a text label and an image icon. They are also given mnemonics so that the jukebox can be controlled par- tially from the keyboard. A combo box generates an action event whenever the user makes a selection from it. The JukeBox program uses one action listener class for the combo box and another for both of the push buttons. They could be combined if desired. The actionPerformed method of the ComboListener class is executed when a selection is made from the combo box. The current audio selection that is play- ing, if any, is stopped. The current clip is then updated to reflect the new selec- tion. Note that the audio clip is not immediately played at that point. The user must press the play button to hear the new selection. 550 CHAPTER 9 graphical user interfaces listing 9.14 //******************************************************************** // JukeBox.java Author: Lewis/Loftus // // Demonstrates the use of a combo box. //******************************************************************** import javax.swing.*; public class JukeBox { // // Creates and displays the controls for the juke box. // public static void main (String[] args) { JFrame frame = new JFrame ("Java Juke Box"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JukeBoxControls controlPanel = new JukeBoxControls(); frame.getContentPane().add(controlPanel); frame.pack(); frame.show(); } } display 9.4 additional components 551 listing 9.15 //******************************************************************** // JukeBoxControls.java Author: Lewis/Loftus // // Represents the control panel for the juke box. //******************************************************************** import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.applet.AudioClip; import java.net.URL; public class JukeBoxControls extends JPanel { private JComboBox musicCombo; private JButton stopButton, playButton; private AudioClip[] music; private AudioClip current; // // Sets up the GUI for the juke box. // public JukeBoxControls() { URL url1, url2, url3, url4, url5, url6; url1 = url2 = url3 = url4 = url5 = url6 = null; // Obtain and store the audio clips to play try { url1 = new URL ("file", "localhost", "westernBeat.wav"); url2 = new URL ("file", "localhost", "classical.wav"); url3 = new URL ("file", "localhost", "jeopardy.au"); url4 = new URL ("file", "localhost", "newAgeRythm.wav"); url5 = new URL ("file", "localhost", "eightiesJam.wav"); url6 = new URL ("file", "localhost", "hitchcock.wav"); } catch (Exception exception) {} music = new AudioClip[7]; music[0] = null; // Corresponds to "Make a Selection " music[1] = JApplet.newAudioClip (url1); music[2] = JApplet.newAudioClip (url2); music[3] = JApplet.newAudioClip (url3); 552 CHAPTER 9 graphical user interfaces listing 9.15 continued music[4] = JApplet.newAudioClip (url4); music[5] = JApplet.newAudioClip (url5); music[6] = JApplet.newAudioClip (url6); JLabel titleLabel = new JLabel ("Java Juke Box"); titleLabel.setAlignmentX (Component.CENTER_ALIGNMENT); // Create the list of strings for the combo box options String[] musicNames = {"Make A Selection ", "Western Beat", "Classical Melody", "Jeopardy Theme", "New Age Rythm", "Eighties Jam", "Alfred Hitchcock's Theme"}; musicCombo = new JComboBox (musicNames); musicCombo.setAlignmentX (Component.CENTER_ALIGNMENT); // Set up the buttons playButton = new JButton ("Play", new ImageIcon ("play.gif")); playButton.setBackground (Color.white); playButton.setMnemonic ('p'); stopButton = new JButton ("Stop", new ImageIcon ("stop.gif")); stopButton.setBackground (Color.white); stopButton.setMnemonic ('s'); JPanel buttons = new JPanel(); buttons.setLayout (new BoxLayout (buttons, BoxLayout.X_AXIS)); buttons.add (playButton); buttons.add (Box.createRigidArea (new Dimension(5,0))); buttons.add (stopButton); buttons.setBackground (Color.cyan); // Set up this panel setPreferredSize (new Dimension (300, 100)); setBackground (Color.cyan); setLayout (new BoxLayout (this, BoxLayout.Y_AXIS)); add (Box.createRigidArea (new Dimension(0,5))); add (titleLabel); add (Box.createRigidArea (new Dimension(0,5))); add (musicCombo); add (Box.createRigidArea (new Dimension(0,5))); add (buttons); add (Box.createRigidArea (new Dimension(0,5))); musicCombo.addActionListener (new ComboListener()); stopButton.addActionListener (new ButtonListener()); 9.4 additional components 553 listing 9.15 continued playButton.addActionListener (new ButtonListener()); current = null; } //***************************************************************** // Represents the action listener for the combo box. //***************************************************************** private class ComboListener implements ActionListener { // // Stops playing the current selection (if any) and resets // the current selection to the one chosen. // public void actionPerformed (ActionEvent event) { if (current != null) current.stop(); current = music[musicCombo.getSelectedIndex()]; } } //***************************************************************** // Represents the action listener for both control buttons. //***************************************************************** private class ButtonListener implements ActionListener { // // Stops the current selection (if any) in either case. If // the play button was pressed, start playing it again. // public void actionPerformed (ActionEvent event) { if (current != null) current.stop(); if (event.getSource() == playButton) if (current != null) current.play(); } } } 554 CHAPTER 9 graphical user interfaces The actionPerformed method of the ButtonListener class is executed when either of the buttons is pushed. The current audio selection that is playing, if any, is stopped. If it was the stop button that was pressed, the task is complete. If the play button was pressed, the current audio selection is played again from the beginning. sliders A slider is a component that allows the user to specify a numeric value within a bounded range. A slider can be presented either vertically or horizontally and can have optional tick marks and labels indicating the range of values. A program called ViewColors is shown in Listing 9.16. It presents three slid- ers that control the RGB components of a color. The color specified by the val- ues of the sliders is shown in a square that is displayed to the right of the sliders. A slider lets the user specify a numeric value within a bounded range. key concept listing 9.16 //******************************************************************** // ViewColors.java Authors: Lewis/Loftus // // Demonstrates the use slider components. //******************************************************************** import java.awt.*; import javax.swing.*; public class ViewColors { // // Presents up a frame with a control panel and a panel that // changes color as the sliders are adjusted. // public static void main (String[] args) { JFrame frame = new JFrame ("View Colors"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 9.4 additional components 555 The panel called colorPanel defined in the main method is used to display (by setting its background color) the color specified by the sliders. Initially, the settings of the sliders are all zero, which correspond to the initial color displayed (black). listing 9.16 continued JPanel colorPanel = new JPanel(); colorPanel.setPreferredSize (new Dimension (100, 100)); colorPanel.setBackground (new Color (0, 0, 0)); Container cp = frame.getContentPane(); cp.setLayout (new FlowLayout()); cp.add (new ViewSliderPanel(colorPanel)); cp.add (colorPanel); frame.pack(); frame.show(); } } display 556 CHAPTER 9 graphical user interfaces The ViewSliderPanel class shown in Listing 9.17 is a panel used to display the three sliders. Each is created from the JSlider class, which accepts four parameters. The first determines the orientation of the slider using one of two JSlider constants (HORIZONTAL or VERTICAL). The second and third parameters specify the maximum and minimum values of the slider, which are set to 0 and 255 for each of the sliders in the example. The last parameter of the JSlider constructor specifies the slider’s initial value. In our example, the initial value of each slider is zero, which puts the slider knob to the far left when the program initially executes. listing 9.17 //******************************************************************** // ViewSliderPanel.java Authors: Lewis/Loftus // // Represents the slider control panel for the ViewColors program. //******************************************************************** import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class ViewSliderPanel extends JPanel { private JPanel colorPanel; private JSlider rSlider, gSlider, bSlider; private JLabel rLabel, gLabel, bLabel; // // Sets up the sliders and their labels, aligning them along // their left edge using a box layout. // public ViewSliderPanel (JPanel panel) { colorPanel = panel; 9.4 additional components 557 listing 9.17 continued rSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0); rSlider.setMajorTickSpacing (50); rSlider.setMinorTickSpacing (10); rSlider.setPaintTicks (true); rSlider.setPaintLabels (true); rSlider.setAlignmentX (Component.LEFT_ALIGNMENT); gSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0); gSlider.setMajorTickSpacing (50); gSlider.setMinorTickSpacing (10); gSlider.setPaintTicks (true); gSlider.setPaintLabels (true); gSlider.setAlignmentX (Component.LEFT_ALIGNMENT); bSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0); bSlider.setMajorTickSpacing (50); bSlider.setMinorTickSpacing (10); bSlider.setPaintTicks (true); bSlider.setPaintLabels (true); bSlider.setAlignmentX (Component.LEFT_ALIGNMENT); SliderListener listener = new SliderListener(); rSlider.addChangeListener (listener); gSlider.addChangeListener (listener); bSlider.addChangeListener (listener); rLabel = new JLabel ("Red: 0"); rLabel.setAlignmentX (Component.LEFT_ALIGNMENT); gLabel = new JLabel ("Green: 0"); gLabel.setAlignmentX (Component.LEFT_ALIGNMENT); bLabel = new JLabel ("Blue: 0"); bLabel.setAlignmentX (Component.LEFT_ALIGNMENT); setLayout (new BoxLayout (this, BoxLayout.Y_AXIS)); add (rLabel); add (rSlider); add (Box.createRigidArea (new Dimension (0, 20))); add (gLabel); add (gSlider); add (Box.createRigidArea (new Dimension (0, 20))); add (bLabel); add (bSlider); } [...]... certain set of events, and only listeners of those types can be added to the component 5 67 10 characterize any software devel- chapter objectives opment effort: requirements, design, implementation, and testing In subsequent chapters, ◗ Explore several different software development models we’ve learned to design and ◗ Explain the life cycle of a software system and its implications for software development... should 570 CHAPTER 10 software engineering 10.0 software development models A program goes through many phases from its initial conception to its ultimate demise This sequence is often called the life cycle of a program Too often programmers focus so much on the particular issues involved in getting a program to run that they ignore other important characteristics Developing high-quality software requires... day-to-day activities of a programmer We explore these issues as we discuss the software life cycle and software development models in this chapter software life cycle All programs go through three fundamental stages: development (with its four basic phases), followed by use, and maintenance Figure 10.1 shows the life cycle of a program Initially, the idea for a program is conceived by a software developer... to the developer, and the program undergoes maintenance Software maintenance is the process of modifying a program in order to enhance it or eliminate deficiencies Unlike hardware, software does not degrade over time Thus, the goal of software maintenance is to produce an improved program rather than a program that is “almost like new.” The changes are made to a copy of the program, so that the user... cycle of a program 10.0 software development models Maintaining software is the process of modifying a program in order to enhance it or to eliminate deficiencies key concept the program is being maintained When the changes are serious or numerous enough, a new version of the program is released for use A program might be maintained many times over, resulting in several releases 571 For a variety of reasons,... general support for the program ◗ key concept ◗ Add non-essential but helpful features to the program The scope of a particular refinement is a tradeoff between the resources available to write the program and the complexity of the program If there are many programmers that will be writing and designing the parts of a particular program, the scope of one refinement for this team of programmers can be larger... necessarily a good program The goal of writing software is not to minimize the amount of time it takes to develop a program, but to minimize the overall amount of effort required to create and maintain a useful program for the long term With this goal in mind, the development process should be well defined and rigorously followed 574 CHAPTER 10 software engineering Write program figure 10.4 Modify program Release... broad, addressing a large portion of a program, or it might be focused on a particular detail of the program Typical refinements might include the following: Create part of the user interface for the program ◗ Develop a particular functional feature of the program ◗ Test the feasibility of a particular program requirement ◗ Establish a specific algorithm to be used in the program ◗ Develop utility classes... amount of time often elapses between the initial development and the maintenance tasks, and often the responsibilities of personnel change Therefore, maintainers often do not understand the software as well as 572 CHAPTER 10 software engineering the original developers did The effort involved in a maintenance task, such as fixing a defect, depends on the maintainer’s ability to understand the program, ... larger than if there is only one programmer The task of each member of the team is defined to assure that the goals of the refinement cycle will be achieved In any case, the goals of each refinement must be well defined The scope of a refinement is a tradeoff between the resources available to write the program and the complexity of the program Refinements allow a programmer to focus on specific issues . but- tons in the program. 9 .7 Design and implement a program that combines the functionality of the StyleOptions and QuoteOptions programs from Chapter 6. That is, the new program should present. GUI’s appearance is a function of the containment hierarchy and the layout managers of each of the containers. ◗ Using the special features of various components often improves a GUI’s functionality. ◗. timing of the stopwatch. 9.9 Design and implement an application that draws the graph of the equation ax 2 + bx + c, where the values of a, b, and c are set using three sliders. 9.10 Design and