”;
A Dialog object is a window that appears on top of the base window with which the user interacts. In this chapter, we shall see the preconfigured dialogs defined in the swing library. They are MessageDialog, ConfirmDialog and InputDialog. They are available because of the static method of the JOptionPane class.
In the following example, the File menu has three JMenu items corresponding to the above three dialogs; each executes the OnClick event handler.
file = JMenu("File") msgbtn = JMenuItem("Message",actionPerformed = OnClick) conbtn = JMenuItem("Confirm",actionPerformed = OnClick) inputbtn = JMenuItem("Input",actionPerformed = OnClick) file.add(msgbtn) file.add(conbtn) file.add(inputbtn)
The OnClick() handler function retrieves the caption of Menu Item button and invokes the respective showXXXDialog() method.
def OnClick(event): str = event.getActionCommand() if str == ''Message'': JOptionPane.showMessageDialog(frame,"this is a sample message dialog") if str == "Input": x = JOptionPane.showInputDialog(frame,"Enter your name") txt.setText(x) if str == "Confirm": s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?") if s == JOptionPane.YES_OPTION: txt.setText("YES") if s == JOptionPane.NO_OPTION: txt.setText("NO") if s == JOptionPane.CANCEL_OPTION: txt.setText("CANCEL")
If the message option from menu is chosen, a message pops up. If Input option is clicked, a dialog asking for the input pops up. The input text is then displayed in the text box in the JFrame window. If the Confirm option is selected, a dialog with three buttons, YES, NO and CANCEL comes up. The user’s choice is recorded in the text box.
The entire code is given below −
from javax.swing import JFrame, JMenuBar, JMenu, JMenuItem, JTextField from java.awt import BorderLayout from javax.swing import JOptionPane frame = JFrame("Dialog example") frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) frame.setLocation(100,100) frame.setSize(400,300) frame.setLayout(BorderLayout()) def OnClick(event): str = event.getActionCommand() if str == ''Message'': JOptionPane.showMessageDialog(frame,"this is a sample message dialog") if str == "Input": x = JOptionPane.showInputDialog(frame,"Enter your name") txt.setText(x) if str == "Confirm": s = JOptionPane.showConfirmDialog (frame, "Do you want to continue?") if s == JOptionPane.YES_OPTION: txt.setText("YES") if s == JOptionPane.NO_OPTION: txt.setText("NO") if s == JOptionPane.CANCEL_OPTION: txt.setText("CANCEL") bar = JMenuBar() frame.setJMenuBar(bar) file = JMenu("File") msgbtn = JMenuItem("Message",actionPerformed = OnClick) conbtn = JMenuItem("Confirm",actionPerformed = OnClick) inputbtn = JMenuItem("Input",actionPerformed = OnClick) file.add(msgbtn) file.add(conbtn) file.add(inputbtn) bar.add(file) txt = JTextField(10) frame.add(txt, BorderLayout.SOUTH) frame.setVisible(True)
When the above script is executed, the following window is displayed with three options in the menu −
Message box
Input Box
Confirm Dialog
”;