import javax.swing.*; import java.awt.*; import java.awt.event.*; /**** * * Class SelectDialog is the pop-up dialog that is displayed when the user * selects the 'Select' item in the 'Draw' menu. * */ public class EditSelectDialog extends JFrame implements ActionListener { /** The model data class, the setSelection method of which we want to * call */ private WorkSpace workSpace; /** The canvas that needs to be redrawn after the selection is made, to * highlight the selected shape. */ DrawingCanvas canvas; /** The text field for user input */ JTextField textField = new JTextField(2); /** The OK button */ JButton okButton = new JButton("OK"); /** X screen coordinate for this display */ final int X_LOCATION = 50; /** Y screen coordinate for this display */ final int Y_LOCATION = 75; /** * The code here is taken from the SetXDialog.java example. */ public EditSelectDialog(WorkSpace workSpace, DrawingCanvas canvas) { /* * Call daddy. */ super(); /* * Set the local data field that refers to the model. This is used * subsequently in the OK button listener. */ this.workSpace = workSpace; /* * Set the local data field for the canvas that needs redrawing. */ this.canvas = canvas; /* * Set up the "OK" button, which the user presses to confirm the input * and dismiss the dialog. */ okButton.addActionListener(new OKButtonListener()); /* * Layout the display using boxes, as done in other 102 examples. */ Box vbox = Box.createVerticalBox(); Box hbox = Box.createHorizontalBox(); hbox.add(new JLabel("Selection Number:")); hbox.add(textField); vbox.add(hbox); vbox.add(okButton); /* * Add the window dressing. This includes moving the window down and * to the right, so that it does not appear directly on top of the * menubar. Note that closing this dialog with an OS close gadget does * NOT close the entire application. That only happens for the * outermost frame of the app. */ setTitle("Enter a selection number"); setLocation(X_LOCATION, Y_LOCATION);; add(vbox); pack(); } public void actionPerformed(ActionEvent e) { setVisible(true); } /** * Inner class that implements the OK button listener. */ public class OKButtonListener implements ActionListener { /** * Get the selection number entered by the user in the text field. If * it parses as an integer, call workSpace.setSelection(int). */ public void actionPerformed(ActionEvent e) { /* * Get and parse the (would-be) numeric user input. */ Integer i = NumericInputParser.parseInRange(textField.getText(), 1, workSpace.size()); /* * If the number is legal, set the current selection to it, and * repaint the canvas. Note that user inputs start at 1, not 0. */ if (i != null) { workSpace.setSelection(i - 1); canvas.repaint(); } /* * Dismiss the dialog. */ setVisible(false); } } }