Example of open dialog
box:
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. import java.io.*;
5.
6. public class OpenMenu extends JFrame implements ActionListener{
7. JMenuBar mb;
8. JMenu file;
9. JMenuItem open;
10. JTextArea ta;
11. OpenMenu(){
12. open=new JMenuItem("Open File");
13. open.addActionListener(this);
14.
15. file=new JMenu("File");
16. file.add(open);
17.
18. mb=new JMenuBar();
19. mb.setBounds(0,0,800,20);
20. mb.add(file);
21.
22. ta=new JTextArea(800,800);
23. ta.setBounds(0,20,800,800);
24.
25. add(mb);
26. add(ta);
27.
28. }
29. public void actionPerformed(ActionEvent e) {
30. if(e.getSource()==open){
31. openFile();
32. }
33. }
34.
35. void openFile(){
36. JFileChooser fc=new JFileChooser();
37. int i=fc.showOpenDialog(this);
38.
39. if(i==JFileChooser.APPROVE_OPTION){
40. File f=fc.getSelectedFile();
41. String filepath=f.getPath();
42.
43. displayContent(filepath);
44.
45. }
46.
47. }
48.
49. void displayContent(String fpath){
50. try{
51. BufferedReader br=new BufferedReader(new FileReader(fpath));
52. String s1="",s2="";
53.
54. while((s1=br.readLine())!=null){
55. s2+=s1+"\n";
56. }
57. ta.setText(s2);
58. br.close();
59. }catch (Exception e) {e.printStackTrace(); }
60. }
61.
62. public static void main(String[] args) {
63. OpenMenu om=new OpenMenu();
64. om.setSize(800,800);
65. om.setLayout(null);
66. om.setVisible(true);
67. om.setDefaultCloseOperation(EXIT_ON_CLOSE);
68. }
69. }
No comments:
Post a Comment