【问题标题】:How can I use an Arraylist in an object for a method in another class如何将对象中的 Arraylist 用于另一个类中的方法
【发布时间】:2015-12-22 23:17:46
【问题描述】:

我的程序应该从用户那里获取单词和定义,并像闪存卡一样显示它们。我已经将所有单词分类到类中,现在我需要做的就是做到这一点,以便当我的应用程序按下按钮时,控制器类将执行一个方法,该方法将通过 Card 类的数组列表并显示单词,最后显示定义。

我的问题是我有一个包含所有卡片的阅读器类的对象,我希望能够在 getWordClick 方法中调用随机卡片。我不知道如何在另一个类中使用该对象。

public class Main extends Application{


@Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Scene.fxml"));
    primaryStage.setTitle("FlashCards");

    Scene scene = new Scene(root, 600, 400, Color.GREY);
    primaryStage.setScene(scene);
    primaryStage.show();
}


public static void main (String[] args){

    Reader r = new Reader();

    //Initialises the Arraylist and reads the file adding them to arraylist
    ArrayList<String> wordList = r.getWordList();
    r.OpenFile();
    r.readFile(wordList);
    r.closeFile();

    //Initialises the Definitions Arraylist and reads the file adding them
    ArrayList<String> definitionList = r.getDefinitionsList();
    r.OpenFile();
    r.readFile(definitionList);
    r.closeFile();

    /* IGNORE IS FOR TESTING PURPOSES
    //Wordlist is printed
    for (String i : wordList){
        System.out.println(i);
    }

    //Definitions list is printed
    for (String i : definitionList){
        System.out.println(i);
    } */

    //Card for each word and def is made
    ArrayList<Card> c = r.getCardList();
    Main m = new Main();
    r.cardSetter(m.addTerms(c, wordList.size(), wordList, definitionList));


    //Loops through and displays the word and defs
    for (Card i : c){
        System.out.printf("%s : %s\n",i.dispWord(),i.dispDef());
    }

    //Displays the window
    launch(args);
}

public ArrayList<Card> addTerms(ArrayList<Card> c, int q, ArrayList<String> word, ArrayList<String> def){
    for (int i = 0; i<q; i++){
        c.add(new Card(word,def,i));
    }
    return c;
}

}

这里是阅读器类

public class Reader {

private Scanner x;
private Scanner sc;

//ArrayList to store the words
private ArrayList<String> wordList = new ArrayList<>();
//ArrayList to store the definitions
private ArrayList<String> definitionsList = new ArrayList<>();
//ArrayList to store the cards
private ArrayList<Card> cardList = new ArrayList<>();


//Simple scanner collects user input
public String getFileName(){
    sc = new Scanner(System.in);
    return sc.nextLine();
}

//Method to open the file and throw an exception if failed
public void OpenFile(){
    try{
        x = new Scanner(new File(getFileName()));
    }
    catch (Exception e){
        System.out.println("could not find file");
    }
}

//Assigns each line to a Array
public void readFile(ArrayList<String> e){
    while(x.hasNext()){
        e.add(x.nextLine());
    }
}

//Closes file
public void closeFile(){
    x.close();
}

//Returns the wordlist
public ArrayList<String> getWordList(){
    return wordList;
}

//Returns Definitionlist
public ArrayList<String> getDefinitionsList(){
    return definitionsList;
}

//Returns cardList
public ArrayList<Card> getCardList(){
    return cardList;
}

public void cardSetter(ArrayList<Card> c){
    c = cardList;
}
}

这里是卡片类

public class Card {

private String word;
private String definition;

public Card(ArrayList<String> Word,ArrayList<String> Definition, int i){
    word = Word.get(i);
    definition = Definition.get(i);
}

public String dispWord(){
    return word;
}

public String dispDef(){
    return definition;
}

}

终于来了控制器

public class Controller {

Random rand = new Random();
private int Random;
//Makes the rand instance variable int so that the def class can use it

public Button wordBox;
public Label defBox;

public void getWordClick(){

}

public void goExit(){

}

public void goRand(){

}

public void getDefClick(){


}

public void goNext(){

}

public void goPrev(){

}

}

对不起,我知道它很长,但代码仅供参考,我主要关心的是如何从Reader r 获取ArrayList&lt;Card&gt;,以便我可以在getWordClick() 方法中的控制器中使用它。从字面上看,任何帮助都会受到赞赏,我只需要有人在我被卡住时将我推向正确的方向。

更新:我现在编辑了控制器类,所以它看起来像这样 公共类控制器 {

Random rand = new Random();
private int Random;
//Makes the rand instance variable int so that the def class can use it

public Button wordBox;
public Label defBox;


private Reader mReader = null;

public Controller(Reader reader){
    this.mReader = reader;
}

public Reader getReader(){
    return this.mReader;
}

public void getWordClick(){
    getReader();
}

public void goExit(){

}

public void goRand(){

}

public void getDefClick(){


}

public void goNext(){

}

public void goPrev(){

}

}

但现在的问题是,当 fxml 文件运行并查找控制器时,它将如何创建对象本身或将使用我创建的对象,因为我创建了一个对象,我在其中添加了阅读器作为构造函数.但是我不知道 fxml 文件将如何使用它来处理事件。

【问题讨论】:

  • 我不认为我理解这个问题。您已经有一个方法getCardList 来检索Reader 的卡片列表。难道你不能只有一个实例变量来存储Reader,然后在getWordClick 中调用reader.getCardList()
  • 您的问题是在处理 List 吗?看一篇教程:examples.javacodegeeks.com/core-java/util/arraylist/…。否则,您可以像任何对象变量一样传递管理它。

标签: java object arraylist javafx controller


【解决方案1】:

虽然我不知道它的内存效率如何,但我看到了一个简单的方法:

在你的控制器类中声明

private Reader mReader = null;

并添加一个构造函数

public Controller(Reader reader)
{
     this.mReader = reader;
}
public Reader getReader()
{
     return this.mReader;
}

因此,您声明 Controller 类的不同之处在于您将读取器对象的引用传递给该类的引用。这是一个被称为封装的概念。

编辑:

可以提供构造函数的类是强大的工具。多态性等是很好的研究课题,在开发方面有很多实际应用。我也打算推荐链接来检查,但我需要自己做更多的研究:p

多态性 java 的快速 google 将为您提供足够多的知识!

EDIT2 代码重复:

读者

public class Reader {

private Scanner x;
private Scanner sc;

//ArrayList to store the words
private ArrayList<String> readContent = new ArrayList<>();
private String filename = "";

public Reader()
{
    //if every time I want a new reader, I want to read user input
    //this.filename = readUserInput();
    //If I want to read indefinitely which I will do for now
    readIndefinitely();
}

//This will continuously read until the user enters a valid file name
public void readIndefinitely()
{
    while (!OpenFile())
    {
        filename = readUserInput();
    }
}
public Reader(String fileIWantToRead)
{
    this.filename = fileIWantToRead;
}

public String readUserInput()
{
    if (sc != null)
    {
       sc.close();
       sc = null;
    }
    sc = new Scanner(System.in);
    return sc.nextLine();
}
//Simple scanner collects user input
public String getFileName(){
    return filename;
}

//Method to open the file and throw an exception if failed
public boolean OpenFile(){
    try{
        //assume we already know the filename
        x = new Scanner(new File(filename));
    }
    catch (Exception e){
        System.out.println("could not find file");
        return false;
    }
    return true;
}

//Assigns each line to a Array
public ArrayList<String> readFile(){
OpenFile();
try
{
    readContent.clear();
    while(x.hasNext()){
        readContent.add(x.nextLine());
    }
}
catch(Exception e)
{
    e.printStackTrace();
}
closeFile();
return readContent;
}

//Closes file
public void closeFile(){
    x.close();
}
public String getReadContent()
{
   return readContent;
}
public void clearReadContent()
{
   readContent.clear();
}
} //end class

卡类

public class Card {
    private String word;
    private String definition;

    public Card(String word, String definition){
        this.word = word;
        this.definition = definition
    }

    public String getWord(){
        return word;
    }

    public String getDefinition(){
    return definition;
    }

}

主类

public class Main extends Application{

    private ArrayList<Card> mCards = new ArrayList<>();
    public Main(ArrayList<Card> cards)
    {
        this.mCards = cards;
        //do what is required to get the cards to the controller either here or start
    }

    @Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("Scene.fxml"));
    primaryStage.setTitle("FlashCards");

    Scene scene = new Scene(root, 600, 400, Color.GREY);
    primaryStage.setScene(scene);
    primaryStage.show();
}

    public static void main (String[] args){

        Reader wordReader = new Reader();
        Reader definitionReader = new Reader();
        wordReader.readFile();
        definitionReader.readFile();

        /* IGNORE IS FOR TESTING PURPOSES
        //Wordlist is printed
        for (String i : wordList){
            System.out.println(i);
        }

        //Definitions list is printed
        for (String i : definitionList){
            System.out.println(i);
        } */

        //if we know that both the words and definitions are the same size, we can make cards
        ArrayList<Card> c = makeCards(wordReader.getReadContent(), definitionReader.getReadContent());
    //Loops through and displays the word and defs
        for (Card i : c){
            System.out.printf("%s : %s\n",i.dispWord(),i.dispDef());
        }

        Main m = new Main(c);
    //Displays the window
        //Not sure how FXMLLoader and this functions as I don't work too much with java but if you pass a reference to main in you'd be good to go
        launch(args);
    }

public ArrayList<Card> makeCards(ArrayList<String> word, ArrayList<String> def){
    ArrayList<Card> cards = new ArrayList<>();
    for (int i = 0; i<word.size(); i++){
        c.add(new Card(word.get(i),def.get(i)));
    }
    return c;
}
}

控制器:

public class Controller {
    Random rand = new Random();
    private int Random;
    //Makes the rand instance variable int so that the def class can use it
    private int position = 0;
    public Button wordBox;
    public Label defBox;
    //instead of passing in an entire reader we just pass in cards (oops!)
    private ArrayList<Card> mCards = new ArrayList<>();

    public Controller(ArrayList<Card> cards){
        this.mCards = cards;
    }

    public ArrayList<Card> getCards()
    {
        return this.mCards;
    }

    public void goExit(){
        //Exit program
    }

    public void goRand(){
        //nextInt in range is ((max - min) + 1) + min and we want a position that corresponds from 0 to the size of cards

        position = rand.nextInt(cards.size());
        wordBox.setText(cards.get(position).getWord());
        defBox.setText(cards.get(position).getDefinition());
    }

    public void getDefClick(){
        //Call to either cards.get(position).getDefinition() or defBox.getText().toString()

    }

    public void goNext(){
        //because retrieving from cards starts at index 0 the equivalent position will require a +1 and we are looking for the next
        if (cards.size() < position+2)
        {
            position++;
            wordBox.setText(cards.get(position).getWord();
            defBox.setText(cards.get(position).getDefinition();
        }
    }

    public void goPrev(){
        //same concept as above but assume that position is already an acceptable value
        if (position != 0 && !cards.isEmpty())
        {
            position--;
            wordBox.setText(cards.get(position).getWord());
            defBox.setText(cards.get(position).getDefinition());
        }
    }
}

【讨论】:

  • 谢谢,我会试试看效果如何:D
  • 不客气。发表您对此主题可能有的任何问题,我会尽力再次回答。
  • 所以我将您告诉我的内容添加到了控制器类中,这非常有意义,因为现在制作控制器对象时,它将需要一个读者。但另一个问题是,当 fxml 文件查找控制器时,它会构建一个对象,如果是,我在哪里声明它将使用的对象。因为这是我现在最关心的问题。我知道如何将阅读器添加到控制器类,但如何让 fxml 类使用我在其中使用阅读器制作的对象。
  • 我为你添加了更多信息
  • 感谢您的帮助,但没关系,我想出了另一种方法,我得到了它的工作:D
【解决方案2】:

在我看来,您只是需要更多地练习面向对象的设计概念。

让我们从逻辑上看这个问题。你有一个Controller 类,它被用来控制Cards 列表的视图。这里明显的问题是您的 Controller 实际上缺少要控制的 Cards 列表,因此,您应该将其添加到类中。

public class Controller {
    // The list of Cards that are being controlled.
    private ArrayList<Card> cards;

    ...
}

现在这只是增加了Controller 的抽象概念。显然,我们需要一种方法来指定Controller 应该使用哪个Cards 列表。因此,我们应该创建一个构造函数。

public class Controller {
    // The list of Cards that are being controlled.
    private ArrayList<Card> cards;

    ...

    // A list of cards must be specified when creating a Controller instance.
    public Controller(ArrayList<Card> cards) {
        this.cards = cards;
    }

    ...
}

或者,您可以使用 mutator 方法(也称为 setter 方法)使用称为封装的概念来设置卡片列表,如 KoalaKoalified 所述。

public class Controller {
    // The list of Cards that are being controlled.
    private ArrayList<Card> cards;

    ...

    // Specify a list of cards.
    public void setCards(ArrayList<Card> cards) {
        this.cards = cards;
    }

    ...
}

所以现在,在 Main 中,或者在您创建 Controller 实例的任何地方,您都可以这样做:

Controller controller = new Controller(r.getCardList());

或者,如果您更喜欢使用 mutator 方法,则:

Controller controller = new Controller();
controller.setCards(r.getCardList());

现在,您的 Controller 类可以在其每个方法中引用 Cards 列表,如果您有其他提供 Cardss 列表的源,它可能会被重用。

我强烈建议对面向对象设计 (OOD) 进行更多研究。 Java 非常依赖这种类型的设计。您似乎在程序中散布了一些零碎的东西,但您似乎对某些细节以及可能的全局有些困惑。

【讨论】:

  • 当 FXML 文件运行时,当我按下按钮时,它会使用我在 main 中创建的控制器对象来执行方法吗?因为我正在使用 Java FX 来制作应用程序。如果我在控制器类中有一个事件处理程序,它会使用我在 main 中创建的对象来处理点击事件吗?
  • 我会试试你的建议,看看效果如何:D 非常感谢。
  • 鉴于 OP 加载 FXML 的方式,您不应自己调用 Controller 构造函数,因为您获得的实例不可能是连接到由FXML 文件。要么展示如何在FXMLLoader 中设置控制器,要么展示如何检索它创建的实例。
  • @James_D 我能做些什么来解决这个问题?
猜你喜欢
  • 2014-09-21
  • 1970-01-01
  • 2017-12-20
  • 2015-07-12
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多