将HashMap的值设置为标签的文本

问题描述 投票:1回答:1

我正在尝试将标签的文本设置为Hashmap中的值,但是我只获得为标签重复的HashMap的最后一个值。我希望我的标签与此类似-> Reference Image

但是我只能得到这个-> My Image

我尝试了许多不同的方法来遍历HashMap,但是它们都导致我仅获得每个标签的HashMap的最后一个值。

这是我的代码:

调用api并解析Json的类->我使用地图,但是如果您知道更好的方法,请告诉我

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class EventfulApi implements EventsAPIInterface {

    private static HttpURLConnection connection;

    //Constants
    private static String baseUrl = "http://api.eventful.com/json/";
    private static String apiKey = "&app_key=KH7kFfxFkzKGnkLf";

    private static String categories = "categories/list?&";

    //Event Request URL's
    private static final String musicEvents = "events/search?keywords=music&";
    private static final String comedyEvents = "events/search?keywords=comedy&";
    private static final String educationEvents = "events/search?keywords=education&";
    private static final String festivalEvents = "events/search?keywords=festival&";
    private static final String exhibitsEvents = "events/search?keywords=exhibits&";
    private static final String attractionEvents = "events/search?keywords=attractions&";

    /**
     *
     * @param _zipcode
     * @return
     * @throws JSONException
     * @throws MalformedURLException
     * @throws ProtocolException
     * @throws IOException
     */
    @Override
    public ArrayList<Map> loadCategories() throws JSONException, MalformedURLException, ProtocolException, IOException {

        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();

        URL url = new URL(baseUrl + categories + apiKey);

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        int status = connection.getResponseCode();

        ArrayList<Map> mapsOfCategories = new ArrayList<Map>();

        if (status > 299) {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            while ((line = reader.readLine()) != null) {
                responseContent.append(line);
            }
            reader.close();
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                responseContent.append(line);
            }
            reader.close();
        }

        JSONObject obj = new JSONObject(responseContent.toString());

        JSONArray arr = (JSONArray) obj.get("category");

        Map<Integer, String> categoriesMap = new LinkedHashMap<Integer, String>();

        JSONObject categories;

        for (int i = 0; i < arr.length(); i++) {

            categories = (JSONObject) arr.get(i);
            categoriesMap.put(i, categories.getString("name").replaceAll("&amp;", "and"));
        }

        mapsOfCategories.add(categoriesMap);

        connection.disconnect();

        return mapsOfCategories;
    }

    /**
     *
     * @param _zipcode
     * @return
     * @throws JSONException
     * @throws MalformedURLException
     * @throws ProtocolException
     * @throws IOException
     */
    @Override
    public ArrayList<Map> loadComedyEventsByZipcode(int _zipcode) throws JSONException, MalformedURLException, ProtocolException, IOException {

        BufferedReader reader;
        String line;
        StringBuffer responseContent = new StringBuffer();

        URL url = new URL(baseUrl + comedyEvents + "l=" + _zipcode + "&within=25&units=miles&" + apiKey);

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        int status = connection.getResponseCode();

        ArrayList<Map> mapsOfMusicEvents = new ArrayList<Map>();

        if (status > 299) {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            while ((line = reader.readLine()) != null) {
                responseContent.append(line);
            }
            reader.close();
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                responseContent.append(line);
            }
            reader.close();
        }

        JSONObject obj = new JSONObject(responseContent.toString());
        JSONObject events = obj.getJSONObject("events");

        JSONArray arr = events.getJSONArray("event");

        Map<Integer, String> musicEventsMap = new HashMap<Integer, String>();

        JSONObject titles;

        for (int i = 0; i < arr.length(); i++) {

            titles = arr.getJSONObject(i);
            musicEventsMap.put(i, titles.getString("title"));
        }

        mapsOfMusicEvents.add(musicEventsMap);

        connection.disconnect();

        return mapsOfMusicEvents;
    }

}

接口类->

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Map;
import org.json.JSONException;

public interface EventsAPIInterface {

    public ArrayList<Map>  loadComedyEventsByZipcode(int _zipcode) throws JSONException, MalformedURLException, ProtocolException, IOException;

    public ArrayList<Map>  loadCategories() throws JSONException, MalformedURLException, ProtocolException, IOException;

}

适配器类->

import java.io.IOException;
import java.net.ProtocolException;
import java.util.ArrayList;
import java.util.Map;
import org.json.JSONException;

public class EventsAPIAdapter {

    protected static final EventsAPIInterface currentlyUsedApi = (EventsAPIInterface) new EventfulApi();

    public ArrayList<Map> loadComedyEventsByZipcode(int _zipcode) throws JSONException, ProtocolException, IOException{
        return EventsAPIAdapter.currentlyUsedApi.loadComedyEventsByZipcode(_zipcode);
    }

  public ArrayList<Map> loadCategories() throws JSONException, ProtocolException, IOException{
        return EventsAPIAdapter.currentlyUsedApi.loadCategories();
    }

}


模型类->

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import org.json.JSONException;

public class EventsModel {

    private int zipcode;

    private Map comedyEventVenueMap;

    private Map categoriesMap;

    private static final int comedyEventMapINDEX = 0;

    private static final int categoriesMapINDEX = 0;

    protected final static EventsAPIAdapter adapter = new EventsAPIAdapter();

    public static EventsModel loadEventsByZipcode(int _zipcode) throws IOException, JSONException{
        EventsModel useModel = new EventsModel();
        ArrayList<Map> tempStorageForMaps = adapter.loadComedyEventsByZipcode(_zipcode);

        useModel.setZipcode(_zipcode);

        Map comedyMap = tempStorageForMaps.get(comedyEventMapINDEX);
        useModel.setComedyEventVenueMap(comedyMap);

        return useModel;      
    }

    public static EventsModel loadCategories() throws IOException, JSONException{
        EventsModel useModel = new EventsModel();
        ArrayList<Map> tempStorageForMaps = adapter.loadCategories();

        Map categoriesMap = tempStorageForMaps.get(categoriesMapINDEX);
        useModel.setCategoriesMap(categoriesMap);

        return useModel;         
    }

    //=================  GETTERS ===============
    public int getZipcode() {
        return zipcode;
    }

    public Map getComedyEventVenueMap() {
        return comedyEventVenueMap;
    }

    public Map getCategoriesMap() {
        return categoriesMap;
    }


    //=================  SETTERS ===============
    public void setZipcode(int zipcode) {
        this.zipcode = zipcode;
    }

    public void setComedyEventVenueMap(Map musicEventVenueMap) {
        this.comedyEventVenueMap = musicEventVenueMap;
    }

    public void setCategoriesMap(Map categoriesMap) {
        this.categoriesMap = categoriesMap;
    }
}


控制器类->

import Controller.EventsModel;
import java.io.IOException;
import java.util.Map;
import javafx.scene.image.ImageView;
import org.json.JSONException;

public class EventsController {


    public EventsController() {
    }

    private int zipcode;
    protected EventsModel eventsModel = new EventsModel();   

    //=================  GETTERS ===============

    public Map getComedyMap() throws IOException, JSONException {
        this.eventsModel = eventsModel.loadEventsByZipcode(this.zipcode);
        return this.eventsModel.getComedyEventVenueMap();
    }

    public Map getCategoriesMap() throws IOException, JSONException{
        this.eventsModel = eventsModel.loadCategories();
        return this.eventsModel.getCategoriesMap();
    }

}


启动应用程序的主类->


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

public class EventsUI extends Application {

    @Override
    public void start(Stage _stage) throws Exception {

        Parent root = FXMLLoader.load(getClass().getResource("Events.fxml"));
        Scene scene = new Scene(root);
        _stage.setScene(scene);
        _stage.show();
    }

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

}

我正在尝试将标签设置为HashMap的主屏幕类->

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import org.json.JSONException;
import View.EventsController;

public class EventsView implements Initializable {

    @FXML
    protected ListView<String> categoriesListView;

    private FlowPane eventsFlowPane;

    @FXML
    private ScrollPane eventsScrollPane;

    protected Map<Integer, String> categoriesMap;

    private EventsController eventsController = new EventsController();

    // Builds the poster flow pane by populating with poster views
    private void buildEventsFlowPane() throws JSONException, IOException {

        // Build a flow pane layout with the width and size of the
        eventsFlowPane = new FlowPane(Orientation.HORIZONTAL);
        eventsFlowPane.setHgap(50);
        eventsFlowPane.setVgap(10);
        eventsFlowPane.setPadding(new Insets(10, 8, 4, 8));
        // bind to scroll pane width
        eventsFlowPane.prefWrapLengthProperty().bind(eventsScrollPane.widthProperty());   

        this.categoriesMap = eventsController.getCategoriesMap();
        for (int i = 0; i < this.categoriesMap.size(); i++) {
            AnchorPane posterPane = buildEventPane();
            eventsFlowPane.getChildren().add(posterPane);
        }
        eventsScrollPane.setContent(eventsFlowPane);
    }

    // Builds the pane
    private AnchorPane buildEventPane() throws JSONException, IOException
    {
        try
        {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(EventsView.class.getResource("EventsMainScreenView.fxml"));
            AnchorPane posterView = loader.load();

            EventsMainScreen controller = loader.getController();

        for (int i = 0; i < this.categoriesMap.size(); i++) {

           controller.getEventName().setText((String) this.categoriesMap.get(i));

        }


           return posterView;
        }
        catch (IOException ex){
            System.err.println("Failed to load");
            ex.printStackTrace();
        }
        return null;
    }

    /**
     * This method adds the categories to the listview
     */
    public void addCategoriesToList() throws IOException, JSONException {
        this.categoriesMap = eventsController.getCategoriesMap();
        for (int i = 0; i < this.categoriesMap.size(); i++) {
            this.categoriesListView.getItems().add((String) this.categoriesMap.get(i));
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        try {
            addCategoriesToList();
        } catch (IOException ex) {
            Logger.getLogger(EventsView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JSONException ex) {
            Logger.getLogger(EventsView.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            try {
                buildEventsFlowPane();
            } catch (IOException ex) {
                Logger.getLogger(EventsView.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (JSONException ex) {
            Logger.getLogger(EventsView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


我传递给MainScreen的Pan类,以创建多个Poster(我知道我应该重命名该类)

public class EventsMainScreen
{
    @FXML
    private Label eventName;

    @FXML
    private ImageView eventImage;

    @FXML
    private AnchorPane eventAcPane;

    public AnchorPane ACP(){
        return eventAcPane;
    }

    public Label getEventName() {
        return eventName;
    }

    public void newLabel(){
         eventName = new Label();
        // return eventName;
    }

    public void setEventName(Label eventName) {
       this.eventName = eventName;
    }

    public ImageView getEventImage() {
        return eventImage;
    }

    public void setEventImage(ImageView eventImage) {
        this.eventImage = eventImage;
    }
}

EventsView FXML

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

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.control.Menu?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="1333.0" stylesheets="@css.css" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="View.EventsView">
   <left>
      <VBox fx:id="mMovieTypeVBox" alignment="TOP_CENTER" prefHeight="709.0" prefWidth="273.0" spacing="8.0" styleClass="pane" stylesheets="@css.css" BorderPane.alignment="CENTER">
         <children>
            <Label styleClass="titleLabel" text="Explore" />
            <ListView fx:id="categoriesListView" prefHeight="664.0" prefWidth="185.0" VBox.vgrow="ALWAYS" />
         </children>
         <padding>
            <Insets bottom="10.0" left="10.0" right="10.0" top="6.0" />
         </padding>
      </VBox>
   </left>
   <center>
      <AnchorPane prefHeight="687.0" prefWidth="997.0" BorderPane.alignment="CENTER">
         <children>
            <ScrollPane fx:id="eventsScrollPane" hbarPolicy="NEVER" layoutX="22.0" prefHeight="709.0" prefWidth="1138.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="2.0" AnchorPane.topAnchor="0.0">
              <content>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="200.0" prefWidth="200.0" />
              </content>
            </ScrollPane>
         </children>
      </AnchorPane>
   </center>
   <bottom>
      <HBox alignment="BOTTOM_LEFT" spacing="10.0" BorderPane.alignment="CENTER">
         <padding>
            <Insets bottom="4.0" left="10.0" right="10.0" top="4.0" />
         </padding>
      </HBox>
   </bottom>
   <top>
      <VBox styleClass="pane" stylesheets="@css.css" BorderPane.alignment="CENTER">
         <children>
            <MenuBar prefHeight="50.0" prefWidth="80.0" styleClass="pane" stylesheets="@css.css">
              <menus>
                <Menu mnemonicParsing="false" text="Profile">
                  <items>
                  </items>
                </Menu>
              </menus>
            </MenuBar>
            <HBox alignment="BASELINE_LEFT" spacing="20.0">
               <children>
                  <Label prefHeight="16.0" prefWidth="123.0" text="Search Events" />
                  <Label fx:id="test" prefHeight="21.0" prefWidth="723.0" text="Label" />
               </children>
               <padding>
                  <Insets bottom="6.0" left="10.0" right="10.0" top="6.0" />
               </padding>
            </HBox>
         </children>
      </VBox>
   </top>
</BorderPane>


EventsMainScreen FXML

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

<?import javafx.scene.control.Label?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>

<AnchorPane fx:id="eventAcPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="200.0" prefWidth="120.0" styleClass="posterPane" stylesheets="@Main_Styles.css" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="View.EventsMainScreen">
   <children>
      <VBox alignment="TOP_CENTER" prefHeight="200.0" prefWidth="120.0" spacing="4.0" styleClass="pane" stylesheets="@css.css" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <children>
            <ImageView fx:id="eventImage" fitHeight="179.0" fitWidth="122.0" pickOnBounds="true" preserveRatio="true" />
            <Label fx:id="eventName" styleClass="subtitle" text="Label" wrapText="true" />
         </children>
      </VBox>
   </children>
</AnchorPane>

EventsView类中的Anchor Pane方法是我的主要问题所在,categoryMap.get(i)仅返回地图中的最后一个值,我也尝试过使用:

int count = 0;
for(int i = 0; i < categoriesMap.size(); i++){
count++;

然后controller.getEventName()。setText((String)this.categoriesMap.get(count));

但是那也不起作用

任何建议都非常感谢,谢谢。

java json javafx hashmap maps
1个回答
0
投票

没有测试您的代码,我想您的错误是在此代码部分中:

// Builds the pane
private AnchorPane buildEventPane() throws JSONException, IOException
{
    try
    {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(EventsView.class.getResource("EventsMainScreenView.fxml"));
        AnchorPane posterView = loader.load();

        EventsMainScreen controller = loader.getController();

    for (int i = 0; i < this.categoriesMap.size(); i++) {

       controller.getEventName().setText((String) this.categoriesMap.get(i));

    }


       return posterView;
    }
    catch (IOException ex){
        System.err.println("Failed to load");
        ex.printStackTrace();
    }
    return null;
}

检查EventsMainScreen controller = loader.getController();确实是在创建控制器对象的新instance。还要检查您是否没有重构具有相同label文本的控制器的所有实例。这就是为什么您在for循环的最后一次运行中获得相同结果的原因。

尝试创建新的控制器实例,并使用setController对其进行显式设置,如下例所示:

EventsMainScreen controller = new EventsMainScreen();
loader.setController(controller);
// after that -> load it
AnchorPane posterView = loader.load();
© www.soinside.com 2019 - 2024. All rights reserved.