ActionPerformed方法不允许我抛出IOException,那么在执行某个动作时如何读取.txt文件呢?谢谢你的帮助。
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Word puzzle generator")) {
file=textN.getText()+".txt";
row=Integer.valueOf(textR.getText());
col=Integer.valueOf(textC.getText());
System.out.println(file+row+col);
readfile(file);
}
}
答案 0 :(得分:1)
actionPerformed
方法由事件派发线程执行。该线程负责更新GUI。当您在此线程中读取文件时,它将阻止用户界面。此类操作应在自己的线程上完成。这可以通过SwingWorker
方便地完成,如以下示例所示,该示例读取名为example.txt
的文件:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
public class ReadFileFromGui
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton readFileButton = new JButton("Read file");
readFileButton.addActionListener(e -> readFile());
f.getContentPane().add(readFileButton);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static void readFile()
{
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>()
{
@Override
protected Void doInBackground() throws Exception
{
try
{
doReadFile();
}
catch (IOException e)
{
JOptionPane.showMessageDialog(
null, "Error: "+e.getMessage());
}
return null;
}
@Override
protected void done()
{
JOptionPane.showMessageDialog(
null, "Finished reading file");
}
};
worker.execute();
}
private static void doReadFile() throws IOException
{
String fileName = "example.txt";
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(fileName))))
{
while (true)
{
String line = br.readLine();
if (line == null)
{
break;
}
System.out.println("Read: "+line);
}
}
}
}
答案 1 :(得分:0)
你需要包装到try-catch块中:
try {
readfile(file);
}
catch (IOException ex) {
throw new RuntimeException(ex);
}