对于Java编程和Netbeans IDE来说,我是一个相当新的人,如果对大多数人来说这是一个简单的问题,那么我很抱歉。
但是,我希望在单击按钮时运行以下代码:
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == fileChooser.APPROVE_OPTION){
File file = fileChooser.getSelectedFile();
Scanner InFile = new Scanner(new FileReader(file));
while(InFile.hasNext())
{
String string1 = InFile.next();
System.out.print(" " + string1);
}
问题是为了让这段代码正确运行,我认为在方法减速后它需要throws IOException
?
所以....在Netbeans中我创建了一个鼠标点击事件,并为我创建了以下内容:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
但是......我需要它来代替:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) throws IOException {
问题是Netbeans似乎将这部分代码设置为某种READ-ONLY,并且我无法附加所需的代码。
因此,我的问题很简单。如何将throws IOException
代码添加到需要的位置?
答案 0 :(得分:1)
您需要在方法内使用try / catch子句而不是throws子句。
try {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == fileChooser.APPROVE_OPTION){
File file = fileChooser.getSelectedFile();
Scanner InFile = new Scanner(new FileReader(file));
while(InFile.hasNext()) {
String string1 = InFile.next();
System.out.print(" " + string1);
}
} catch(IOException e) {
e.printStackTrace(); // or handle in some other way
}
我还建议不要使用GUI构建器,或者至少尝试手动创建GUI。构建器可能允许您单击以创建内容,但它们通常不会在严肃的项目中使用(生成的代码变得非常混乱)。此外,如果您只使用GUI构建器,那么您将无法了解Swing是如何工作的。