2016-11-24 3 views
1

Try and Catchを完了する際に問題が発生しています。私はシンタックスエラーが発生し続けます。 "(" "{" ";トークンはどこに必要でないのかを調べました。私のコードはTry&Catchの構文エラー

import javax.swing.JOptionPane; 

import javafx.application.Application; 
import javafx.event.ActionEvent; 
import javafx.event.EventHandler; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.MenuBar; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.VBox; 
import javafx.scene.web.WebEngine; 
import javafx.scene.web.WebHistory; 
import javafx.scene.web.WebView; 
import javafx.stage.Stage; 

public class Browser extends Application{ 

final Button Back = new Button("<-"); 
final Button Forward = new Button ("->"); 
final Button Home = new Button("Home"); 
final Button Reload = new Button("r"); 
final MenuBar menuBar = new MenuBar(); 
final TextField txt = new TextField(); 

@Override 
public void start(Stage stage) throws Exception{ 
    VBox hBox = new VBox(); 
    WebView wv = new WebView(); 
    WebEngine engine = wv.getEngine(); 
    WebHistory wh = engine.getHistory(); 
    engine.load("https://www.google.com"); 

    txt.setOnAction(new EventHandler<ActionEvent>(){ 
     try{ 
      public void handle(ActionEvent event){ 
       engine.load(txt.getText()); 
      } 
     }catch(Exception e){ 
      showError("Unable to load site"); 
     } 
    }); 
    hBox.getChildren().setAll(txt, wv); 

    Scene scene = new Scene(hBox, 800, 600); 
    stage.setTitle("Anthony Gayflor-CS260 OOP"); 
    stage.setScene(scene); 
    stage.show(); 

} 

private void showError(String errorMessage){ 
    JOptionPane.showMessageDialog(this, errorMessage, "Error", JOptionPane.ERROR_MESSAGE); 
} 

public static void main(String[] args){ 
    Application.launch(args); 
} 
} 

である私はそれをコンパイルするとき、私が手にエラーがtry-catchブロックはメソッドの内部でなければなりません

Caused by: java.lang.Error: Unresolved compilation problems: 
Syntax error, insert "}" to complete ClassBody 
Syntax error, insert ")" to complete MethodInvocation 
Syntax error, insert ";" to complete Statement 
Syntax error on token "(", ; expected 
Syntax error on token ")", ; expected 
Syntax error on tokens, delete these tokens 

at Browser.start(Browser.java:33) 
+3

try-catchブロックにメソッドをラップすることはできません。 – Eran

+0

try-catch inside> public void handle(ActionEventイベント) – vvtx

+0

私はあなたが正しいと思う –

答えて

0

イェンスの答えに加えて、 、あなたはでラムダを使用することができますJava 8は、EventHandlerが機能的なインタフェースであるためです。あなたのコードは次のようになります:

txt.setOnAction(event -> { 
    try { 
     engine.load(txt.getText()); 
    }catch (Exception e) { 
     showError("Unable to load site"); 
    } 
}); 
0

です:

public void handle(ActionEvent event){ 
    try{ 
      engine.load(txt.getText()); 
    }catch(Exception e){ 
      showError("Unable to load site"); 
    } 
} 
0

try/catch節でメソッドを定義することはできません!

try/catch節をメソッドに配置します。