300 likes | 458 Views
Building Applications. Dialogs Passing data between windows Validating Input using FocusListeners. Dialogs. Dialogs are windows that appear on top of the main window Used when the application need further to provide or request information to/from the user. Dialogs. 2 kinds of dialog
E N D
Building Applications Dialogs Passing data between windows Validating Input using FocusListeners
Dialogs • Dialogs are windows that appear on top of the main window • Used when the application need further to provide or request information to/from the user
Dialogs 2 kinds of dialog • simple message popped up to the user (JOptionPane[static classes]) • information message, confirmation required from user, short input required from user (e.g. password) • more complex (JDialog) • E.g. Filechooser
Simple dialogs: JOptionPane • JOptionPane class can be used for most simple dialogs e.g. Message with an set of choices Single Message with an OK button JOptionPane class obviously provides some way of configuring the message, configuring buttons, icons etc. ..
JOptionPane Class • Has a set of static methods for the types of simple dialogs you might want to create.: • static methods – showXXXDialog • showMessageDialog= a simple one-button dialog • showConfirmDialog = asks user to confirm with standard Yes/No buttons • showInputDialog = gets a string from the user • showOptionDialog = customised Dialog • variety of buttons, customised button text • customised messages, icons, etc
Static Methods ofJOptionPan class • Which of the following methods of the JOptionClass for which dialog? • showMessageDialog () • showOptionDialog () • showConfirmDialog () • showInputDialog ()
Static Methods ofJOptionPan class • showMessageDialog • showOptionDialog • showConfirmDialog • showInputDialog
JOptionPane • static methods – showXXXDialog • showMessageDialog = a simple one-button dialog • showConfirmDialog = asks user to confirm with standard Yes/No buttons • showInputDialog = gets a string from the user • showOptionDialog = customised Dialog • variety of buttons, customised button text • customised messages, icons, etc Remember to handle the response from the user
JDialog Object Component Container Window Dialog JDialog Frame JFrame • more complex (JDialog) than simple dialogs supported by JOptionPane • E.g. Filechooser
FileChooser dialog • JFileChooser API • Methods all: setting directory, file types, etc
Dialogs Dialogs can be • modal • user forced to interact with the dialog before continuing (e.g. JOptionPane dialogs) • non modal • user can interact with other windows/dialogs while dialog is displayed Modal can be disruptive to user • use it wisely…
Creating Dialogs Creating a JDialog you should specify • owner = parent for dialogwhen owner is destroyed so are child dialogs • title • modal setting when true, blocks input to all other windows in the program Various constructors e.g. JDialog (Frame owner, String title, boolean modal)
JDialog • JDialogs work like Jframes (i.e. they are windows with content..) • setContentPane() • setDefaultCloseOperation() • setVisible() • pack() • New • setLocationRelativeTo( Component) • centers the dialog over the specified component
Passing data between windows • In an application data needs to pass from window to window…
Passing data between windows Different ways: • include methods in dialog class to get data from the dialog, getXXX() • for simple data • Not too much data to be transferred • use an object • A special object to store all info to be transferred to/from dialogue • Good for more complicated data structures/validation • More flexible • Usually referred to as a “data transfer object”
Data Transfer Object • Create an object that encapsulates all data to be transferred between windows • Just define the data as attributes, and put in get /set methods • The contents of the object completely depends on what data you’re transferring between dialog and frame. • E.g. transferring a “find” and “replace” string
Data transfer object (DTO) E.g. transferring a “find” and “replace” string: the DTO Needs to hold both strings, and provide methods for setting and retrieving them (getting) public class DTO{ private String findStr = “”; private String replStr = “”; public String getFindStr(){ return findStr; } public String getReplStr(){ return replStr; } public void setAll(String fs, String rs){ this.findStr = fs; this.replStr = rs; } }
How to implement a dialog with data transfer • So to use a dialog that requires passing data. E.g. Need 1.. Code in the frame that creates the dialog 2.. A dialog class 3.. A Data transfer class to hold the data This is the frame that calls the dialog (clicking the “add” button) This is the dialog
Implementing a dialog with data transfer • JFrame as normal: public class MyDialogTest extends JFrame implements SomeSortOfListener { // Include the DTO and Dialog as attributes in your frame DTO dto; MyDialog dialog = null; … … }
(1) JFrame Class • include listener and event handler that initiates dialog • instantiate DTO object and pass to dialog in the constructor /** in event handler… e.g. in Action Performed method after user has clicked a button or menu bar that results in a dialog being displayed….**/ if (dialog == null) { // first time user selects to open dialog, instantiate the dialog dialog = new MyDialog(this, dto); } Else / not first time, dialog already exists, just show the dialog (set visible) // Control then returns from displaying dialog // extract the data from the DTO and use it – control comes back to here… String findStr = dto.getFindStr(); // etc …
(2) Data Transfer Object • Data transfer object • Holds the various data to be transferred – as discussed • In this case… first name/ surname
(3) Dialog Class class MyDialog extends JDialog implements SomeSortofListener{ private DTO dto; private JFrame owner; MyDialog(parameters in to the contructor..){ super(parameters in to Jdialogsuperclass constructor); this.dto= dto; // format the content pane with controls… // set relative position to owner etc.. } public void eventHandler(Event e) {// validate data entered from dialog controls (optional) // extract all data from dialog controls and // pass to DTO } public void showDialog(){ // Make the dialog visible } better to hide and show dialog than instantiate it each time it is requested
Predefined Dialogs There are dialogs set up already for your use because they are used so often e.g.: • JColorChooser • static method that displays colour dialog and returns colour/null • JFileChooser • includes methods to open the standard Open dialog and Save dialog
JFileChooser //Create a file chooser JFileChooserfc = new JFileChooser(); ... //In response to a button click: intreturnVal = fc.showOpenDialog(aComponent); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would //open the file. … } else { // user cancelled from dialog … }
Handling Focus • A component gains focus when • the user clicks it • the user tabs to it • the user interacts with it • FocusEvents are fired whenever a component gains/loses focus.. Examples of what might happen on losing focus? • FocusListener will ‘listen’ for FocusEvents on components it is registered with • 2 event handlers: public void focusGained(FocusEvent e) public void focusLost(FocusEvent e)
Handling Focus • To give focus to a component: • Use the requestFocusInWindow() method • To make sure a particular textfield has focus whenever the window is displayed: • override the windowActivated event handler of the WindowListener addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { textField.requestFocusInWindow(); } });
Example // text field components private JTextFieldfirstname, surname; // button components private JButton save, cancel; ……….. // Make firstnametextField get the focus whenever frame is activated. addWindowListener(new WindowAdapter() { public void windowGainedFocus(WindowEvent e) { firstname.requestFocusInWindow(); save.setEnabled(false); } });
Using Focus for Handling Input • “Engineering for Errors” • E.g. Enabling/Disabling buttons when user can/should not use them (e.g. in Animal Match game..) • E.g. Validate input before enabling Save button • Use FocusListener: • Register the focusListener with the textfields • Override the focusLost event handler to check that there is text is all required fields • If so, enable Save • Remember to disable Save each time window is displayed
LAB • On any frame that you’ve developed so far, add functionality so that when the “X “ button is pressed on the top right, a message is displayed asking the user if they are sure they want to exit.
LAB Then.. Create a frame that shows a dialog when the “add” button is pressed. The dialog takes a Firstname, surname, and displays it back on the frame