简体   繁体   中英

Calling an arrayList from another class which is private

I am trying to display an arraylist in a gui. However I am getting some troubles. I need to check if my game is legal, if it is not legal then it calls getProblems which displays the arraylist. I tried to call getProblems directly in the GUI class however it will show the array as empty. (Since it's not checking if it's legal). I also tried to call isLegal then getProblems but you cannot do this in a JOptionPane . Any tips on how I can call it accross?

GetProblems class

 protected List < String > getProblems() {
     return displayOutput;
 }

IsLegal Class

public boolean isLegal() {
  boolean legality;

  if (checkRowConstraints().isEmpty()) {
    legality = true;

  } else {
    getProblems();
    legality = false;

  }
  return legalCheck;
}

GUI:

 public void actionPerformed(ActionEvent e) {
     if (!(puzzle.isLegal())) {
       JOptionPane.showMessageDialog(FutoshikiFrame.this,
         puzzle.getProblems(),
         "You made a mistake!",
         JOptionPane.INFORMATION_MESSAGE);

Here is difference between Actual display of GUI result and result i'm trying to get.

GUI的实际显示结果和我试图得到的结果

Further Problem found: I need to return the arraylist then empty it. Fixed

Presently, there is an implicit call to the List 's toString() method when you call puzzle.getProblems() within the JOptionPane . So rather than get the contents of the List , which is what you want, you're getting whatever toString() is giving you.

You're not going to get the contents of the List unless you iterate over it first.

You could try something like this. (Note, this is untested code. For demo purposes.)

String formattedString = "";
//let's iterate over our List and build a formatted string for output
for(String element : puzzle.getProblems())
{
    formattedString += element;
}

Then you can output this formatted String

 public void actionPerformed(ActionEvent e) {
     if (!(puzzle.isLegal())) {
       JOptionPane.showMessageDialog(FutoshikiFrame.this,
         formattedString,
         "You made a mistake!",
         JOptionPane.INFORMATION_MESSAGE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM