我有一個關於偵聽器內try/catch塊的問題。我試圖實現一個JDialog,它爲我提供了保存JTextArea文本的路徑。在我的代碼中,我試着保存文件,並且還有catch部分的消息。如果我插入了錯誤的路徑,我需要更改哪些內容才能捕獲(發出消息)?(Java)如何使用try和catch裏面的actionlistener?
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();
}
}
你是什麼意思是:我需要改變,使我的捕捉只捕捉什麼(給出一個消息)如果我插入了錯誤的路徑? – ifly6
此時,代碼在我給出正確的路徑或錯誤的路徑時起作用。通過正確的路徑,它保存文件,但是catch也返回消息(「不可能保存文件」)。錯誤的路徑只是返回消息。任何事情都必須是錯誤的,當Try部分起作用時,爲什麼他們也會返回catch信息?我在這部分代碼中做錯了什麼? – Babi
我不明白什麼'通過正確的路徑,它保存文件,但catch還返回消息'或'爲什麼他們也返回catch消息'的意思。 – ifly6