Swing - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Dialogues

Swing Dialogues

shape Description

Swing Dialogues is used to provide the communication between the user and the system and most of the dialogues are used to display warning messages and alert messages. Swing dialogues are categorized as custom dialogues and standard Swing Dialogues, custom dialogues will be created by developers such as JDialogue and standard dialogues are predefined like JFileChooser and these are available in Swing API. JDialogue is the class that inherits the properties from AWT dialogue. Examples are shown as below.

Dialogue

shape Example

Below is the source code to perform Swing Dialogues in Swing window application. SwingDialogues.java [java]package swing; import java.awt.Container;//developer needs to import all the required packages import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.GroupLayout; import static javax.swing.GroupLayout.DEFAULT_SIZE; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class SwingDialogues extends JFrame {//created the class and that should must extends JFrame private JPanel pnl; public SwingDialogues() { initUI();//method } private void initUI() { pnl = (JPanel) getContentPane(); JButton warBtn = new JButton("Alert");//message dialog JButton errBtn = new JButton("Exception");//message dialog JButton queBtn = new JButton("Question");//message dialog JButton infBtn = new JButton("Quit");//message dialog warBtn.addActionListener(new ActionListener() {//ActionListener() is a interface that needs to be implemented for ActionEvent @Override public void actionPerformed(ActionEvent event) {//for every button developer has to create actionPerformed JOptionPane.showMessageDialog(pnl, "A warning call!",//to get the message dialogue,developer has to create a method i.e is showMessageDialog() of JOptionPane ,provide parent of the dialogue, text, title, message type. "Warning", JOptionPane.WARNING_MESSAGE); } }); errBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(pnl, "Could not open file!", "Error", JOptionPane.ERROR_MESSAGE); } }); queBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(pnl, "Are you sure to Restart?", "Question", JOptionPane.QUESTION_MESSAGE); } }); infBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(pnl, "Download completed.", "Information", JOptionPane.INFORMATION_MESSAGE); } }); createLayout(warBtn, errBtn , queBtn, infBtn); setTitle("Message dialogs");//set the title setSize(300, 200);//set the bounds setLocationRelativeTo(null);//it means that frame needs to be at center of the system setDefaultCloseOperation(EXIT_ON_CLOSE);//to close the window } private void createLayout(JComponent... arg) { Container pane = getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addContainerGap(DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(gl.createParallelGroup() .addComponent(arg[0]) .addComponent(arg[2])) .addGroup(gl.createParallelGroup() .addComponent(arg[1]) .addComponent(arg[3])) .addContainerGap(DEFAULT_SIZE, Short.MAX_VALUE) ); gl.setVerticalGroup(gl.createSequentialGroup() .addContainerGap(DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(gl.createParallelGroup() .addComponent(arg[0]) .addComponent(arg[1])) .addGroup(gl.createParallelGroup() .addComponent(arg[2]) .addComponent(arg[3])) .addContainerGap(DEFAULT_SIZE, Short.MAX_VALUE) ); gl.linkSize(arg[0], arg[1], arg[2], arg[3]); pack(); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { SwingDialogues md = new SwingDialogues(); md.setVisible(true); } }); } }[/java] Create a class that should extend the JFrame and also create the constructor that should be same as class name. [java]public class SwingDialogues extends JFrame public SwingDialogues() { initUI();//method }[/java] Create the buttons that need to visible in window of an application. [java]JButton warBtn = new JButton("Alert"); JButton errBtn = new JButton("Exception"); JButton queBtn = new JButton("Question"); JButton infBtn = new JButton("Quit");[/java] Add ActionListener to the all buttons. When user click on those buttons some action will be performed. [java]queBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { JOptionPane.showMessageDialog(pnl, "Are you sure to Restart?", "Question", JOptionPane.QUESTION_MESSAGE);[/java] Create layouts to the all those buttons, titles, size, write the method to close an application. [java]createLayout(warBtn, errBtn , queBtn, infBtn); setTitle("Message dialogs");//set the title setSize(300, 200);//set the bounds setLocationRelativeTo(null);//it means that frame needs to be at center of the system setDefaultCloseOperation(EXIT_ON_CLOSE);[/java] Create the gap between the components by creating object to the group layout. [java]GroupLayout gl = new GroupLayout(pane); gl.setAutoCreateGaps(true);[/java] Create the main method and create an object to the class. [java]public static void main(String[] args) SwingDialogues md = new SwingDialogues(); md.setVisible(true);[/java]

Output:

After executing the above code successfully, output will be as follows. Where each button will have it's own message dialogue. Where window has four boxes and each box will consists of it's message, for instance when click on quit button, it displays The output as follows.

CustomDialogue

shape Example

Below is the source code to implement custom dialogues in an application. CustomDialogue.java [java]package swing; import java.awt.Container;//import all the required pacakges import java.awt.EventQueue; import java.awt.Font; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.Box; import javax.swing.GroupLayout; import static javax.swing.GroupLayout.Alignment.CENTER; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; class AboutDialog extends JDialog {//created a class i.e is AboutDialog (custom dialogue)that should extends the JDialog public AboutDialog(Frame parent) { super(parent);//used super keyword to get the parent properties initUI();//method } private void initUI() { ImageIcon icon = new ImageIcon("notes.png");//creating image JLabel label = new JLabel(icon); JLabel name = new JLabel("Notes, 1.23"); name.setFont(new Font("Serif", Font.BOLD, 13));//setting font size JButton btn = new JButton("OK");//creating ok button btn.addActionListener(new ActionListener() {//ActionListener is a interface that needs to be implemented on created button. @Override public void actionPerformed(ActionEvent event) { dispose(); } }); createLayout(name, label, btn); setModalityType(ModalityType.APPLICATION_MODAL);// setModalityType() is used to set the quality of the model setTitle("About Notes");//created the title setDefaultCloseOperation(DISPOSE_ON_CLOSE);//to close the window setLocationRelativeTo(getParent());//to keep the window in middle of the screen } private void createLayout(JComponent... arg) { Container pane = getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateContainerGaps(true); gl.setAutoCreateGaps(true); gl.setHorizontalGroup(gl.createParallelGroup(CENTER) .addComponent(arg[0]) .addComponent(arg[1]) .addComponent(arg[2]) .addGap(200) ); gl.setVerticalGroup(gl.createSequentialGroup() .addGap(30) .addComponent(arg[0]) .addGap(20) .addComponent(arg[1]) .addGap(20) .addComponent(arg[2]) .addGap(30) ); pack(); } } public class CustomDialogue extends JFrame //CustomDialogue is extending the JFrame implements ActionListener {//implemented the ActionListener interface public CustomDialogue() { initUI();//method } private void initUI() { createMenuBar();//to create the menu setTitle("Simple Dialog");//set the title setSize(350, 250);//set the boundaries setLocationRelativeTo(null);//set the locaton of the window setDefaultCloseOperation(EXIT_ON_CLOSE);//window will be closed } private void createMenuBar() { JMenuBar menubar = new JMenuBar(); JMenu fileMenu = new JMenu("File");//creating menu file fileMenu.setMnemonic(KeyEvent.VK_F); JMenu helpMenu = new JMenu("Help");//creating menu help helpMenu.setMnemonic(KeyEvent.VK_H); JMenuItem aboutMi = new JMenuItem("About");//creating menu about aboutMi.setMnemonic(KeyEvent.VK_A); helpMenu.add(aboutMi);//click on help i.e displays about aboutMi.addActionListener(this); menubar.add(fileMenu); menubar.add(Box.createGlue()); menubar.add(helpMenu); setJMenuBar(menubar); } @Override public void actionPerformed(ActionEvent e) { showAboutDialog(); } private void showAboutDialog() { AboutDialog ad = new AboutDialog(this); ad.setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { CustomDialogue sd = new CustomDialogue(); sd.setVisible(true); } }); } }[/java] Create a class that should extend from JDialogue and it is not the main class.Here import the super keyword to get the properties. [java]class AboutDialog extends JDialog {//created a class i.e is AboutDialog (custom dialogue)that should extends the JDialog public AboutDialog(Frame parent) { super(parent);[/java] Create the image icon, label, button and add the ActionListener to this button, when user click on the button action will be invoked. [java]ImageIcon icon = new ImageIcon("notes.png"); JLabel label = new JLabel(icon); JLabel name = new JLabel("Notes, 1.23"); name.setFont(new Font("Serif", Font.BOLD, 13)); JButton btn = new JButton("OK");//creating ok button btn.addActionListener(new ActionListener()[/java] Write setModalityType() method to set the quality of an application. [java]setModalityType(ModalityType.APPLICATION_MODAL);[/java] Create the file menu, help menu components and add menu items to the help menu. [java]JMenu fileMenu = new JMenu("File");//creating menu file fileMenu.setMnemonic(KeyEvent.VK_F); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic(KeyEvent.VK_H); JMenuItem aboutMi = new JMenuItem("About"); aboutMi.setMnemonic(KeyEvent.VK_A); helpMenu.add(aboutMi);[/java]

Output:

After executing the above code successfully, output will be as follows. Where window consists of two menu bars File and Help. When click on the Help menu then it shows About dialogue that consists the text message is as follows.

FileChooser

shape Example

Below is the source code to choose the files from an application window. FileChooserEx.java [java]package swing;//create the package import java.awt.Container;// import the required packages import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.GroupLayout; import static javax.swing.GroupLayout.DEFAULT_SIZE; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; public class FileChooserEx extends JFrame {//Create a class FileChooserEx that should extend JFrame private JPanel panel; private JTextArea area; public FileChooserEx() { initUI();//method } private void initUI() { panel = (JPanel) getContentPane(); area = new JTextArea(); JScrollPane spane = new JScrollPane(); spane.getViewport().add(area); JToolBar toolbar = createToolBar(); createLayout(toolbar, spane); setTitle("JFileChooser"); setSize(400, 300); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private JToolBar createToolBar() { ImageIcon open = new ImageIcon("document-open.png"); JToolBar toolbar = new JToolBar();//creating object to the JToolBar JButton openb = new JButton(open); openb.addActionListener(new OpenFileAction()); toolbar.add(openb);//to open the tool bar return toolbar; } private void createLayout(JComponent... arg) { Container pane = getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); gl.setHorizontalGroup(gl.createParallelGroup() .addComponent(arg[0], DEFAULT_SIZE, DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(gl.createSequentialGroup() .addComponent(arg[1])) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(4) .addComponent(arg[1]) ); pack(); } public String readFile(File file) { String content = ""; try { content = new String(Files.readAllBytes(Paths.get( file.getAbsolutePath()))); } catch (IOException ex) { Logger.getLogger(FileChooserEx.class.getName()).log( Level.SEVERE, null, ex); } return content; } private class OpenFileAction extends AbstractAction {//created class OpenFileAction that should extends AbstractAction @Override public void actionPerformed(ActionEvent e) {//it needs to be performed when user click on the button or event JFileChooser fdia = new JFileChooser();//constructor of the dialogue which user chose FileFilter filter = new FileNameExtensionFilter("Java files", "java");//file will be filtered fdia.addChoosableFileFilter(filter); int ret = fdia.showDialog(panel, "Open file");//showDialog displays the dialogue on the screen if (ret == JFileChooser.APPROVE_OPTION) { File file = fdia.getSelectedFile(); String text = readFile(file); area.setText(text); } } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() {//The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe. @Override public void run() { FileChooserEx fcd = new FileChooserEx(); fcd.setVisible(true); } }); } }[/java] Create a class FileChooserEx that should extends from the JFrame.Create a panel and text field and create a constructor that should be same as class name. [java]public class FileChooserEx extends JFrame { private JPanel panel; private JTextArea area; public FileChooserEx(){}[/java] Create a toolbar, place the document open image, create the object to the toolbar and add the toolbar into the open button.ActionListener should perform on the open button, when user click on open button required files will be opened. [java]JToolBar createToolBar() { ImageIcon open = new ImageIcon("document-open.png"); JToolBar toolbar = new JToolBar();//creating object to the JToolBar JButton openb = new JButton(open); openb.addActionListener(new OpenFileAction()); toolbar.add(openb);[/java] While reading the file exception may be happened then debug the data with try and catch blocks. [java]try { content = new String(Files.readAllBytes(Paths.get( file.getAbsolutePath()))); } catch (IOException ex) { Logger.getLogger(FileChooserEx.class.getName()).log( Level.SEVERE, null, ex);[/java] Created the method to filter the files while choosing. [java]FileFilter filter = new FileNameExtensionFilter("Java files", "java");[/java] Write the main method, create the object to the class and place the invokelater() method. [java]public static void main(String[] args) { EventQueue.invokeLater(new Runnable() {//The invokeLater() method places the application on the Swing Event Queue. It is used to ensure that all UI updates are concurrency-safe. @Override public void run() { FileChooserEx fcd = new FileChooserEx(); fcd.setVisible(true); } }); } } [/java] Output: After executing the above code successfully, output will be as follows. In an application, user can choose the file from the document list and user can open it.

Summary

shape Key Points

  • Swing Dialogues - setLocationRelativeTo() used to keep the window in center of the screen.
  • Swing Dialogues - setModalityType() used to check and set the quality of the model.
  • Swing Dialogues - setDefaultCloserOperation(DISPOSE_); is used to close the window otherwise developer has to use Taskmanager in the system, it takes more time.