是否可以使用ArrayList中的对象在JavaFx和Scene Builder中设置标签和单选按钮? [英] Is it possible to use objects in an ArrayList to set labels and radio buttons in JavaFx and Scene Builder?

查看:287
本文介绍了是否可以使用ArrayList中的对象在JavaFx和Scene Builder中设置标签和单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个多选电影游戏,其中电影出现在标签中,并且演员与该电影匹配,并且3个randoms被设置为单选按钮。我在网上找到的每个示例或教程都向我展示了如何在不实现已编写的任何类或对象的情况下使用JavaFx和Scene Builder。我有一个名为MovieSet的类,它接收电影的Arraylist,我也和演员一样。然而,所有在线教程都没有说明是否可以为这些arraylist设置标签和单选按钮。



是否可以这样做?怎么会这样呢?



我用了一个for循环迭代了movieList,但它告诉我它找不到movieList的符号

  public static void displayMovies(ArrayList< Movie> movieList){
for(int x = 0; x< movieList.size (); x ++){
电影电影= movieList.get(x);
System.out.printf(%s,movie.toString());
}
}

这是我的控制器。我很抱歉。这是我第一次使用JavaFX和

 公共类FXMLDocumentController实现Initializable {

@FXML
private Label movielabel;

@FXML
private void handleButtonAction(ActionEvent event){

}

@Override
public void initialize(URL url,ResourceBundle rb){
MovieSet movie = new MovieSet();
this.movi​​elabel.getLabelFor(MovieSet.displayMovies(movieList));
}

}


解决方案

此示例应用是处理多项选择问答应用的一般方法。代码中的注释。


主类




  import javafx.application.Application; 
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

/ **
*
* @author blj0011
* /
公共类MultipleChoiceGameExample扩展应用
{

@Override
public void start(阶段阶段)抛出异常
{
父root = FXMLLoader.load(getClass()。getResource(FXMLDocument.fxml));

场景场景=新场景(根);

stage.setScene(场景);
stage.show();
}

/ **
* @param args命令行参数
* /
public static void main(String [] args)
{
launch(args);
}

}




控制器




  import java.net.URL; 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;

/ **
*
* @author blj0011
* /
公共类FXMLDocumentController实现Initializable
{

@FXML
private Label lblQuestionNumber;
@FXML
private TextArea taQuestionDisplay;
@FXML
private Button btnAnswer1,btnAnswer2,btnAnswer3,btnAnswer4,btnNextQuestion;

列表<问题>问题;
int currentQuestion = 0;

@Override
public void initialize(URL url,ResourceBundle rb)
{
//从数据库中获取问题或者使用什么来源
FakeDatabaseHandler fakeDatabaseHandler = new FakeDatabaseHandler();
questions = fakeDatabaseHandler.getQuestions();
//随机播放问题
Collections.shuffle(问题);
//加载第一个问题
lblQuestionNumber.setText(问题1+ questions.size());
loadQuestion(questions.get(currentQuestion));
}

@FXML
public void handleBtnNextQuestion(ActionEvent actionEvent)
{
currentQuestion ++;
if(currentQuestion< questions.size()){
lblQuestionNumber.setText(Question+(currentQuestion + 1)+of+ questions.size());
loadQuestion(questions.get(currentQuestion));
}
else {
警报警报=新警报(Alert.AlertType.WARNING);
alert.setTitle(Game Over Alert);
alert.setContentText(没有其他问题!);
alert.showAndWait();
}
}

public void loadQuestion(问题)
{
taQuestionDisplay.setText(question.getQuestion()); //设置问题
List< String> choices = question.getIncorrectAnswers(); //获取错误答案
choices.add(question.getCorrectAnswer()); ////获取正确答案并添加。
Collections.shuffle(选项); //随机选择

//向List添加按钮,以便更轻松地创建事件处理程序
List< Button> choicesButtons = new ArrayList();
choicesButtons.add(btnAnswer1);
choicesButtons.add(btnAnswer2);
choicesButtons.add(btnAnswer3);
choicesButtons.add(btnAnswer4);
//将选项设置为Button
for(int i = 0; i< choices.size(); i ++){
choicesButtons.get(i).setText(choices。得到(I));
}

//为每个按钮创建动作处理程序
for(按钮按钮:choicesButtons){
button.setOnAction(actionEvent - > {
//检查按钮的文本是否等于正确答案
if(button.getText()。equals(question.getCorrectAnswer())){
警报警报=新警报(Alert.AlertType.INFORMATION);
alert.setTitle(Answer Alert);
alert.setHeaderText(Correct!);
alert.setContentText(你的答案是正确的!);
alert .showAndWait();
}
else {
警报警报=新警报(Alert.AlertType.INFORMATION);
alert.setTitle(回答警报);
alert.setHeaderText(不正确!);
alert.setContentText(你的答案错了!\ n正确答案我s+ question.getCorrectAnswer());
alert.showAndWait();
}
});
}

}

}



< blockquote>

FXML




 <?xml version =1.0 encoding =UTF-8?> 

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>

< AnchorPane id =AnchorPaneprefHeight =476.0prefWidth =668.0xmlns:fx =http://javafx.com/fxml/1xmlns =http:// javafx.com/javafx/8.0.141fx:controller =multiplechoicegameexample.FXMLDocumentController>
< children>
< Label fx:id =labellayoutX =126layoutY =120minHeight =16minWidth =69/>
< VBox alignment =TOP_CENTERprefHeight =200.0prefWidth =100.0AnchorPane.bottomAnchor =0.0AnchorPane.leftAnchor =0.0AnchorPane.rightAnchor =0.0AnchorPane.topAnchor =0.0 >
< children>
< Label fx:id =lblQuestionNumberalignment =CENTERmaxWidth =1.7976931348623157E308text =Label/>
< TextArea fx:id =taQuestionDisplayprefHeight =300.0prefWidth =200.0>
< VBox.margin>
< Insets bottom =10.0left =10.0right =10.0top =10.0/>
< /VBox.margin>
< / TextArea>
< GridPane hgap =5.0maxWidth =400.0vgap =5.0>
< columnConstraints>
< ColumnConstraints hgrow =SOMETIMESminWidth =10.0prefWidth =100.0/>
< ColumnConstraints hgrow =SOMETIMESminWidth =10.0prefWidth =100.0/>
< / columnConstraints>
< rowConstraints>
< RowConstraints minHeight =10.0prefHeight =30.0vgrow =SOMETIMES/>
< RowConstraints minHeight =10.0prefHeight =30.0vgrow =SOMETIMES/>
< / rowConstraints>
< children>
< Button fx:id =btnAnswer1maxHeight =1.7976931348623157E308maxWidth =1.7976931348623157E308mnemonicParsing =falsetext =Button/>
< Button fx:id =btnAnswer2maxHeight =1.7976931348623157E308maxWidth =1.7976931348623157E308mnemonicParsing =falsetext =ButtonGridPane.columnIndex =1/>
< Button fx:id =btnAnswer3maxHeight =1.7976931348623157E308maxWidth =1.7976931348623157E308mnemonicParsing =falsetext =ButtonGridPane.rowIndex =1/>
< Button fx:id =btnAnswer4maxHeight =1.7976931348623157E308maxWidth =1.7976931348623157E308mnemonicParsing =falsetext =ButtonGridPane.columnIndex =1GridPane.rowIndex =1 />
< / children>
< / GridPane>
< Button fx:id =btnNextQuestiononAction =#handleBtnNextQuestiontext =Next Question>
< VBox.margin>
< Insets top =20.0/>
< /VBox.margin>
< / Button>
< / children>
< / VBox>
< / children>
< / AnchorPane>




问题类




  import java.util.ArrayList; 
import java.util.List;

/ **
*
* @author blj0011
* /
公共类问题
{

私有字符串问题;
private String correctAnswer;
private List< String> incorrectAnswers = new ArrayList();

public Question(String question,String correctAnswer,List< String> incorrectAnswers)
{
this.question = question;
this.correctAnswer = correctAnswer;
this.incorrectAnswers = incorrectAnswers;
}

public String getQuestion()
{
return question;
}

public void setQuestion(String question)
{
this.question = question;
}

public String getCorrectAnswer()
{
return correctAnswer;
}

public void setCorrectAnswer(String correctAnswer)
{
this.correctAnswer = correctAnswer;
}

public List< String> getIncorrectAnswers()
{
return incorrectAnswers;
}

public void setIncorrectAnswers(List< String> incorrectAnswers)
{
this.incorrectAnswers = incorrectAnswers;
}
}




数据库处理程序(你可以从不同的来源获取您的数据)




  import java.util.ArrayList; 
import java.util.List;

/ **
*
* @author blj0011
* /
公共类FakeDatabaseHandler
{

列表与LT;问题> questions = new ArrayList();

public FakeDatabaseHandler()
{
//连接数据库!
//模拟从db获取数据!
List< String> incorrectAnswersQuestion1 = new ArrayList();
incorrectAnswersQuestion1.add(巴基斯坦);
incorrectAnswersQuestion1.add(Palau);
incorrectAnswersQuestion1.add(Panama);
questions.add(新问题(这是唯一一个以字母'p'开头的美国州?,宾夕法尼亚州,wrongAnswersQuestion1));
List< String> incorrectAnswersQuestion2 = new ArrayList();
incorrectAnswersQuestion2.add(Mississppi);
incorrectAnswersQuestion2.add(尼罗河);
incorrectAnswersQuestion2.add(长江);
questions.add(新问题(世界上最长的河流是什么?,亚马逊,不正确的问题2));
List< String> incorrectAnswersQuestion3 = new ArrayList();
incorrectAnswersQuestion3.add(6,000英里);
incorrectAnswersQuestion3.add(10,000英里);
incorrectAnswersQuestion3.add(12,000英里);
questions.add(新问题(地球的直径是多少?,8,000英里,不正确的问题3));
}

公开列表<问题> getQuestions()
{
返回问题;
}

}


I am trying to create a multiple choice movie game where a movie appears in the label and the actor matched with that movie and 3 randoms are set as the radio buttons. Every example or tutorials I have found online show me how to use JavaFx and Scene Builder without implementing any classes or objects already written. I have a class called MovieSet that takes in an Arraylist of movies, and I do the same with the actors. However all the tutorials online never say if its possible to set the labels and radio buttons to these arraylist.

Is it possible to do this? and if so how would this be done?

I have used a for loop to iterate over the movieList, but it is telling me it cannot find symbol for movieList

public static void displayMovies(ArrayList<Movie> movieList) {
    for (int x = 0; x < movieList.size(); x++) {
        Movie movie = movieList.get(x);
        System.out.printf("%s", movie.toString());
    }
}

This is my controller. I do apologize. This is my first time using JavaFX and

public class FXMLDocumentController implements Initializable {

    @FXML
    private Label movielabel;

    @FXML
    private void handleButtonAction(ActionEvent event) {

    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
       MovieSet movie = new MovieSet(); 
       this.movielabel.getLabelFor(MovieSet.displayMovies(movieList));
    }    

}

解决方案

This sample app is a general way of handling a multiple choice question and answer app. Comments in code.

Main Class

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

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

    @Override
    public void start(Stage stage) throws Exception
    {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

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

}

Controller

import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;

/**
 *
 * @author blj0011
 */
public class FXMLDocumentController implements Initializable
{

    @FXML
    private Label lblQuestionNumber;
    @FXML
    private TextArea taQuestionDisplay;
    @FXML
    private Button btnAnswer1, btnAnswer2, btnAnswer3, btnAnswer4, btnNextQuestion;

    List<Question> questions;
    int currentQuestion = 0;

    @Override
    public void initialize(URL url, ResourceBundle rb)
    {
        //Get Questions from Database or what ever source you use
        FakeDatabaseHandler fakeDatabaseHandler = new FakeDatabaseHandler();
        questions = fakeDatabaseHandler.getQuestions();
        //Shuffle the questions
        Collections.shuffle(questions);
        //Load first question
        lblQuestionNumber.setText("Question 1 of " + questions.size());
        loadQuestion(questions.get(currentQuestion));
    }

    @FXML
    public void handleBtnNextQuestion(ActionEvent actionEvent)
    {
        currentQuestion++;
        if (currentQuestion < questions.size()) {
            lblQuestionNumber.setText("Question " + (currentQuestion + 1) + " of " + questions.size());
            loadQuestion(questions.get(currentQuestion));
        }
        else {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("Game Over Alert");
            alert.setContentText("There are no more questions!");
            alert.showAndWait();
        }
    }

    public void loadQuestion(Question question)
    {
        taQuestionDisplay.setText(question.getQuestion());//Set the question
        List<String> choices = question.getIncorrectAnswers();//Get the incorrect answers
        choices.add(question.getCorrectAnswer());////Get the correct answer and add it.
        Collections.shuffle(choices);//Randomize the choices

        //Add buttons to List to make creating event handlers easier
        List<Button> choicesButtons = new ArrayList();
        choicesButtons.add(btnAnswer1);
        choicesButtons.add(btnAnswer2);
        choicesButtons.add(btnAnswer3);
        choicesButtons.add(btnAnswer4);
        //Set the choices to a Button
        for (int i = 0; i < choices.size(); i++) {
            choicesButtons.get(i).setText(choices.get(i));
        }

        //Create Action handlers for each button
        for (Button button : choicesButtons) {
            button.setOnAction(actionEvent -> {
                //Check if button's text equals the correct answer
                if (button.getText().equals(question.getCorrectAnswer())) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("Answer Alert");
                    alert.setHeaderText("Correct!");
                    alert.setContentText("You got the answer right!");
                    alert.showAndWait();
                }
                else {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("Answer Alert");
                    alert.setHeaderText("Incorrect!");
                    alert.setContentText("You got the answer wrong!\nThe correct answer is " + question.getCorrectAnswer());
                    alert.showAndWait();
                }
            });
        }

    }

}

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextArea?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>
<?import javafx.scene.layout.VBox?>

<AnchorPane id="AnchorPane" prefHeight="476.0" prefWidth="668.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.141" fx:controller="multiplechoicegameexample.FXMLDocumentController">
    <children>
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
      <VBox alignment="TOP_CENTER" prefHeight="200.0" prefWidth="100.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <Label fx:id="lblQuestionNumber" alignment="CENTER" maxWidth="1.7976931348623157E308" text="Label" />
            <TextArea fx:id="taQuestionDisplay" prefHeight="300.0" prefWidth="200.0">
               <VBox.margin>
                  <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
               </VBox.margin>
            </TextArea>
            <GridPane hgap="5.0" maxWidth="400.0" vgap="5.0">
              <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
              </columnConstraints>
              <rowConstraints>
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
              </rowConstraints>
               <children>
                  <Button fx:id="btnAnswer1" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Button" />
                  <Button fx:id="btnAnswer2" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Button" GridPane.columnIndex="1" />
                  <Button fx:id="btnAnswer3" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Button" GridPane.rowIndex="1" />
                  <Button fx:id="btnAnswer4" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308" mnemonicParsing="false" text="Button" GridPane.columnIndex="1" GridPane.rowIndex="1" />
               </children>
            </GridPane>
              <Button fx:id="btnNextQuestion" onAction="#handleBtnNextQuestion" text="Next Question">
               <VBox.margin>
                  <Insets top="20.0" />
               </VBox.margin>
            </Button>
         </children>
      </VBox>
    </children>
</AnchorPane>

Question Class

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author blj0011
 */
public class Question
{

    private String question;
    private String correctAnswer;
    private List<String> incorrectAnswers = new ArrayList();

    public Question(String question, String correctAnswer, List<String> incorrectAnswers)
    {
        this.question = question;
        this.correctAnswer = correctAnswer;
        this.incorrectAnswers = incorrectAnswers;
    }

    public String getQuestion()
    {
        return question;
    }

    public void setQuestion(String question)
    {
        this.question = question;
    }

    public String getCorrectAnswer()
    {
        return correctAnswer;
    }

    public void setCorrectAnswer(String correctAnswer)
    {
        this.correctAnswer = correctAnswer;
    }

    public List<String> getIncorrectAnswers()
    {
        return incorrectAnswers;
    }

    public void setIncorrectAnswers(List<String> incorrectAnswers)
    {
        this.incorrectAnswers = incorrectAnswers;
    }
}

Database Handler(You may get your data from a different source)

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author blj0011
 */
public class FakeDatabaseHandler
{

    List<Question> questions = new ArrayList();

    public FakeDatabaseHandler()
    {
        //connect to db!
        //Simulate getting data from db!
        List<String> incorrectAnswersQuestion1 = new ArrayList();
        incorrectAnswersQuestion1.add("Pakistan");
        incorrectAnswersQuestion1.add("Palau");
        incorrectAnswersQuestion1.add("Panama");
        questions.add(new Question("Which is the only American state to begin with the letter 'p'?", "Pennsylvania", incorrectAnswersQuestion1));
        List<String> incorrectAnswersQuestion2 = new ArrayList();
        incorrectAnswersQuestion2.add("Mississppi");
        incorrectAnswersQuestion2.add("Nile");
        incorrectAnswersQuestion2.add("Yangtze");
        questions.add(new Question("What is the world's longest river?", "Amazon", incorrectAnswersQuestion2));
        List<String> incorrectAnswersQuestion3 = new ArrayList();
        incorrectAnswersQuestion3.add("6,000 miles");
        incorrectAnswersQuestion3.add("10,000 miles");
        incorrectAnswersQuestion3.add("12,000 miles");
        questions.add(new Question("What is the diameter of Earth?", "8,000 miles", incorrectAnswersQuestion3));
    }

    public List<Question> getQuestions()
    {
        return questions;
    }

}

这篇关于是否可以使用ArrayList中的对象在JavaFx和Scene Builder中设置标签和单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆