«Back to Home

Core Java

Topics

How To Open Dialog Box In Swing Java

Open Dialog Box in Swing
 
Let’s see an example of open dialog box in Swin, given below.
 
Code
  1. import java.awt.*;  
  2. import javax.swing.*;  
  3. import java.awt.event.*;  
  4. import java.io.*;  
  5. public class DialogBoxExample extends JFrame implements ActionListener {  
  6.     JMenuBar jmb;  
  7.     JMenu file;  
  8.     JMenuItem open;  
  9.     JTextArea jta;  
  10.     DialogBoxExample() {  
  11.         open = new JMenuItem("Open File");  
  12.         open.addActionListener(this);  
  13.         file = new JMenu("File");  
  14.         file.add(open);  
  15.         jmb = new JMenuBar();  
  16.         jmb.setBounds(0060030);  
  17.         jmb.add(file);  
  18.         jta = new JTextArea(600600);  
  19.         jta.setBounds(030700700);  
  20.         add(jmb);  
  21.         add(jta);  
  22.     }  
  23.     public void actionPerformed(ActionEvent e) {  
  24.         if (e.getSource() == open) {  
  25.             openFile();  
  26.         }  
  27.     }  
  28.     void openFile() {  
  29.         JFileChooser jfc = new JFileChooser();  
  30.         int i = jfc.showOpenDialog(this);  
  31.         if (i == JFileChooser.APPROVE_OPTION) {  
  32.             File fl = jfc.getSelectedFile();  
  33.             String filepath = fl.getPath();  
  34.             displayContent(filepath);  
  35.         }  
  36.     }  
  37.     void displayContent(String fpath) {  
  38.         try {  
  39.             BufferedReader br = new BufferedReader(new FileReader(fpath));  
  40.             String s1 = "", s2 = "";  
  41.             while ((s1 = br.readLine()) != null) {  
  42.                 s2 += s1 + "\n";  
  43.             }  
  44.             jta.setText(s2);  
  45.             br.close();  
  46.         } catch (Exception e) {  
  47.             e.printStackTrace();  
  48.         }  
  49.     }  
  50.     public static void main(String[] args) {  
  51.         DialogBoxExample ome = new DialogBoxExample();  
  52.         ome.setSize(600600);  
  53.         ome.setLayout(null);  
  54.         ome.setVisible(true);  
  55.         ome.setDefaultCloseOperation(EXIT_ON_CLOSE);  
  56.     }  
  57. }  
  58.    
65
66
67

Output

68
 
Summary

Thus, we learnt how to open dialog box in Swing Java.