2017-12-15 17 views
-1

현재 Textadventure 작업을하고 있으며 콘솔에서 Scenebuilder를 사용하여 JavaFX로 이동하기로 결정했습니다. 출력용 TextView 및 입력 용 TextField를 사용하고 있습니다. - 의사 결정과 스토리에 더 방법에 대한 더 Eventfilters을TextField에 대한 대기 입력 메소드를 효율적으로 구현하는 방법은 무엇입니까? (JavaFX)

public class Story implements Initializable { 
    public Button startButton; 
    public TextArea textArea; 
    public TextField textField; 
    public EventHandler mainplot; 

    //On startButton pressed 
    public void startGame() { 
     setEventFilters(); 
     begin(); 
    } 

    public void begin() { 
     print("Welcome to the Adventure."); //print is a method for appending String to textArea 
     print("You wake up in your room."); 
     print("Fresh air blows through your window."); 
     print("You get up. What do you want to do?"); 
     print("1. Drink from the magical can."); 
     print("2. Go outside."); 
     textField.addEventFilter(ActionEvent.ACTION, mainplot); 
    } 

    public void magicalCan() { 
     ... 
    } 

    public void goOutside() { 
     ... 
    } 

    public void setEventFilters() { 
     //mainplotFilter 
     mainplot = new EventHandler<ActionEvent>() { 
      public void handle(ActionEvent e){ 
       if(textField.getText().equals("1")) { 
        textField.removeEventFilter(ActionEvent.ACTION, mainplot); 
        magicalCan(); 
       } 
       if(textField.getText().equals("2")) { 
        textField.removeEventFilter(ActionEvent.ACTION, mainplot); 
        goOutside(); 
       } 
      } 
     }; 
    } 

코드가 같은 방식으로 계속 : 이 내 코드 모습입니다. 이제 let's 내가 스토리 내에서 여러 enterkey 입력을 추가 할 말 :

public void begin() { 
     print("Welcome to the Adventure."); 
     //wait for enter to continue 
     print("You wake up in your room."); 
     print("Fresh air blows through your window."); 
     print("You get up. What do you want to do?"); 
     //wait for enter to continue 
     print("1. Drink from the magical can."); 
     print("2. Go outside."); 
     textField.addEventFilter(ActionEvent.ACTION, mainplot); 
    } 

이벤트 핸들러 또는 모든 스토리의 방법을 통해 사용할 수있는 waitForEnterkey() 메소드를 구현하는 가장 효율적인 방법은 무엇입니까?

+1

왜 20-30 개의 이벤트 처리기가 필요합니까? 스토리 라인의 상태를 기반으로 의사 결정을 내릴 수있는 하나의 핸들러가 더 나은 접근 방법입니다. – Geoff

+0

시도하기 전에 간단한'JavaFX' 튜토리얼을 수행하십시오. [여기] (http://tutorials.jenkov.com/javafx/textfield.html)를 시작하십시오. 'Textfield'가 어떻게 작동하는지 이해하지 못합니다. – Sedrick

+0

나는 내 질문을 명확히했다. 한번보세요. – Andrenergy

답변

0

"ActionListener"을 텍스트 필드에 추가하십시오. 텍스트 필드에 포커스가 있고 사용자가 을 입력하면을 입력하면 이벤트가 발생합니다. 텍스트를 검색하려면

textField.getText(); 

을 입력하고 텍스트를 사용중인 EventFilter와 일치시킬 수 있습니다.

+0

제 질문을 명확히했습니다. 한번보세요. – Andrenergy

1

여기에 시도하려는 것을 보여주는 예가 있습니다. 이것은 질문을하고 스토리를 말하지 않지만 이것을하기위한 프로그래밍 아이디어는 매우 유사합니다.

import javafx.application.Application; 
import javafx.scene.Scene; 
import javafx.scene.control.Button; 
import javafx.scene.control.TextArea; 
import javafx.scene.control.TextField; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 

/** 
* 
* @author blj0011 
*/ 
public class JavaFXApplication71 extends Application 
{ 

    String[] questionBank = 
    { 
     "Connie has 15 red marbles and 28 blue marbles. How many more blue marbles than red marbles does Connie have?", 
     "Connie has 15 red marbles and some blue marbles. She has 13 more blue marbles than red ones. How many blue marbles does Connie have?", 
     "Connie has 28 blue marbles. She has 13 more blue marbles than red ones. How many red marbles does Connie have?" 
    }; 
    String[] correctAnswer = 
    { 
     "28 - 15 = 13", "15 + 13 = 28", "28 - 13 = 15" 
    }; 
    String[] answer1Bank = 
    { 
     "28 - 15 = 13", "28 - 13 = 15", "28 - 13 = 15" 
    }; 
    String[] answer2Bank = 
    { 
     "15 + 13 = 28", "15 + 13 = 28", "28 - 15 = 13" 
    }; 
    int currentQuestionCounter = -1;//Keeps up with what question is currently being asked 

    TextArea storyScreen = new TextArea(); 
    TextField userInput = new TextField(); 
    Button btnStart = new Button(); 

    @Override 
    public void start(Stage primaryStage) 
    { 
     storyScreen.setWrapText(true);//Wrap the text in the TextArea 
     storyScreen.setEditable(false);//Don't allow useInput in the storyScreen 

     userInput.setOnAction(actonEvent ->//Retrieve user Input on Enter pressed 
     { 
      TextField tempUserInput = (TextField) actonEvent.getSource();//get a reference to the userInput TextField. 
      switch (tempUserInput.getText())//Switch on that input 
      { 
       case "1": 
        if (answer1Bank[currentQuestionCounter].equals(correctAnswer[currentQuestionCounter])) 
        { 
         storyScreen.appendText("\n\nYou got this right!"); 
         btnStart.setDisable(false); 
        } 
        else 
        { 
         storyScreen.appendText("\n\nYou got this wrong!"); 
        } 
        break; 
       case "2": 
        if (answer2Bank[currentQuestionCounter].equals(correctAnswer[currentQuestionCounter])) 
        { 
         storyScreen.appendText("\n\nYou got this right!"); 
         btnStart.setDisable(false); 
        } 
        else 
        { 
         storyScreen.appendText("\n\nYou got this wrong!"); 
        } 
        break; 
       default: 
        storyScreen.appendText("\n\nYou have to enter a 1 or 2!"); 
        userInput.setText(""); 
      } 
     }); 

     btnStart.setText("Start"); 
     btnStart.setOnAction(actionEvent -> 
     { 
      btnStart.setText("Next"); 
      btnStart.setDisable(true); 
      userInput.requestFocus();//Move the cursor to the userInput TextField 
      getCurrentQuestionSetup(++currentQuestionCounter); 
     }); 

     VBox root = new VBox(); 
     root.getChildren().addAll(storyScreen, userInput, btnStart); 

     Scene scene = new Scene(root, 300, 250); 

     primaryStage.setTitle("Hello World!"); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) 
    { 
     launch(args); 
    } 

    void getCurrentQuestionSetup(int currentQuestion) 
    { 
     if (currentQuestion < questionBank.length) 
     { 
      userInput.setText("");//reset the TextField 
      storyScreen.clear();//reset the TextArea 

      //Add new Question and answer to Textarea 
      storyScreen.setText(questionBank[currentQuestion]); 
      storyScreen.appendText("\n\n1: " + answer1Bank[currentQuestion]); 
      storyScreen.appendText("\n2: " + answer2Bank[currentQuestion]); 
     } 
     else 
     { 
      storyScreen.appendText("\n\nYou have completed this story!"); 
      userInput.setText(""); 
      btnStart.setText("Start"); 
      btnStart.setDisable(false); 
      currentQuestionCounter = -1; 
     } 
    } 
} 
+0

이 작업을 수행했다면 각 부분에 대한 정보와 함께 내 이야기를 부분적으로 저장하는'SQLite' 데이터베이스를 갖게 될 것입니다. 각 스토리 부분의 객체 목록을 작성합니다. 나는 올바른 이야기 부분을 검색하기 위해 핸들러 클래스를 생성 할 것이다. – Sedrick