简体   繁体   English

(Java)如何在动作侦听器内部使用try and catch?

[英](Java)How to use try and catch inside of a actionlistener?

I have a question about the try/catch block inside of a listener. 我对侦听器内部的try / catch块有疑问。 I tried to implement a JDialog that gives me the path for save a text of a JTextArea. 我试图实现一个JDialog,该对话框为我提供了保存JTextArea文本的路径。 In my code I save the file in try and have also the message from the catch part. 在我的代码中,我将文件保存在try中,并且还包含来自catch部分的消息。 What I need to change so that my catch only captured(gives a message) if I have insert a wrong path? 我需要更改什么,以便在插入错误路径时仅捕获(给出消息)捕获的内容?

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class MyFrame extends JFrame{
    public MyFrame() {
        super("SaveText");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        c.setPreferredSize(new Dimension(300, 400));

        final JTextField tFileName = new JTextField();
        final JTextArea tContent = new JTextArea();
        JButton bSave = new JButton("Save to File");
        JButton bReset = new JButton("Reset Content");

        JPanel pFile = new JPanel();
        pFile.setLayout(new GridLayout(2, 2));
        pFile.add(new JLabel("Content:"));
        c.add(pFile, BorderLayout.NORTH);
        JPanel pForm = new JPanel();
        pForm.setLayout(new GridLayout(1, 1));
        pForm.add(tContent);
        c.add(pForm, BorderLayout.CENTER);
        JPanel pButtons = new JPanel();
        pButtons.setLayout(new GridLayout(1, 2));
        pButtons.add(bSave);
        pButtons.add(bReset);
        c.add(pButtons, BorderLayout.SOUTH);

        bSave.addActionListener(new ActionListener() {

             public void actionPerformed(ActionEvent e) {
                  try {
                      JDialog dialog = new JDialog();
                      dialog.setTitle("Path");
                      JButton button= new JButton("Close");
                      dialog.add(tFileName);
                      dialog.add(button);
                      dialog.setSize(300, 100);
                      dialog.setLayout(new GridLayout(1,1));
                      dialog.setVisible(true);
                      tContent.write(new FileWriter(tFileName.getText()));
                      button.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             dialog.dispose();
                          }
                         });
                      } catch (IOException ex) {
                         System.out.println("Not possible to save the file                   ");
                  }
             }
         });
        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        MyFrame test=new MyFrame();
    }

}

You are not doing right thing with your save. 您保存时没有做正确的事。 You are writing content to a non existing file. 您正在将内容写入不存在的文件。 First you get the path, then check if the file on that path exists , then create a file and then finally write the content to the file. 首先,获取路径,然后检查该路径上的文件是否存在,然后创建一个文件,最后将内容写入该文件。 I modified your bSave.addActionListener , to include a save button where you really need to save file. 我修改了bSave.addActionListener ,在您确实需要保存文件的位置添加了一个保存按钮。

Also couple of things , a) you need to use bufferedwriter to write to a file. 还有几件事,a)您需要使用bufferedwriter写入文件。 b) close bufferdwriter after writing. b)写入后关闭bufferdwriter。 c) dialog needs to be final. c)对话必须是最终的。

 bSave.addActionListener(new ActionListener() {

             public void actionPerformed(ActionEvent e) {
                  try
                  {
                      final JDialog dialog = new JDialog();
                      dialog.setTitle("Path");
                      JButton sbutton= new JButton("Save");
                      final JTextField tFileName = new JTextField();
                      JButton cbutton = new JButton( "Close" );
                      dialog.add(tFileName);
                      dialog.add(sbutton);
                      dialog.add(cbutton);
                      dialog.setSize(300, 100);
                      dialog.setLayout(new GridLayout(1,1));
                      dialog.setVisible(true);

                      sbutton.addActionListener(new ActionListener() 
                      {
                        public void actionPerformed(ActionEvent e) 
                        {
                            File file = new File(tFileName.getText());
                            if( !file.exists())
                            {
                              try {

                                BufferedWriter writer = new BufferedWriter( new FileWriter(file));
                                writer.write(tContent.getText());
                                writer.close();
                              } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                  System.out.println("Not possible to save the file   because :  " + "\n" + e1.getMessage() );
                              }

                            }

                        }
                      });

                      cbutton.addActionListener( new ActionListener()
                      {

                        @Override
                        public void actionPerformed(ActionEvent arg0) 
                        {
                            dialog.dispose();

                        }

                      });
                  } 
                  catch (Exception ex) 
                  {
                      ex.printStackTrace();
                  }
             }
         });

With the above change, your new save dialog will look like : 进行上述更改后,新的保存对话框将如下所示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM