将POJO对象放入JTable [英] Getting POJO objects into JTable

查看:60
本文介绍了将POJO对象放入JTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用我使用Gson()提取的POJOS填充JTable.使用调试器,或使用toString()将值打印到控制台,可以看到对象映射成功.我的问题在于用对象填充自定义Jtable.

I'm trying to populate a JTable with POJOS that I've extracted using Gson(). Using the debugger, or by printing the values to the console using toString(), I can see that the mapping of the objects was successful. My problem lies with populating my custom Jtable with the objects.

问题::我的GUI包含一个带搜索字段的按钮,并将其发送到API,该API以JSON格式返回响应,我可以正确映射该映射,但我不知道如何获取数据进入桌子.

Problem: My GUI contains a button that takes a search field, and sends it to an API which returns a response in JSON, which I map correctly but I do not know how to get the data into the table.

我尝试过的操作:addFilings()和insertFilings()方法返回:类型为FilingsTableModel的方法addFilings(Filing)不适用于参数(ExtractorClass)

What I've tried: The addFilings() and insertFilings() methods return: The method addFilings(Filing) in the type FilingsTableModel is not applicable for the arguments (ExtractorClass)

代码

这是带有getters和setters和toString()方法的Filing类:

Here is the Filing Class with getters and setters and toString() method:

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Filing {

    @SerializedName("id")
    @Expose
    private static String id;
    @SerializedName("filing_date")
    @Expose
    private FilingDate filingDate;
    @SerializedName("accepted_date")
    @Expose
    private AcceptedDate acceptedDate;
    @SerializedName("period_end_date")
    @Expose
    private PeriodEndDate periodEndDate;
    @SerializedName("report_type")
    @Expose
    private String reportType;
    @SerializedName("sec_unique_id")
    @Expose
    private String secUniqueId;
    @SerializedName("filing_url")
    @Expose
    private String filingUrl;
    @SerializedName("report_url")
    @Expose
    private String reportUrl;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        Filing.id = id;
    }

    public FilingDate getFilingDate() {
        return filingDate;
    }

    public void setFilingDate(FilingDate filingDate) {
        this.filingDate = filingDate;
    }

    public AcceptedDate getAcceptedDate() {
        return acceptedDate;
    }

    public void setAcceptedDate(AcceptedDate acceptedDate) {
        this.acceptedDate = acceptedDate;
    }

    public PeriodEndDate getPeriodEndDate() {
        return periodEndDate;
    }

    public void setPeriodEndDate(PeriodEndDate periodEndDate) {
        this.periodEndDate = periodEndDate;
    }

    public String getReportType() {
        return reportType;
    }

    public void setReportType(String reportType) {
        this.reportType = reportType;
    }

    public String getSecUniqueId() {
        return secUniqueId;
    }

    public void setSecUniqueId(String secUniqueId) {
        this.secUniqueId = secUniqueId;
    }

    public String getFilingUrl() {
        return filingUrl;
    }

    public void setFilingUrl(String filingUrl) {
        this.filingUrl = filingUrl;
    }

    public String getReportUrl() {
        return reportUrl;
    }

    public void setReportUrl(String reportUrl) {
        this.reportUrl = reportUrl;
    }

    public String toString() {
        return "[id: " + id + ", Filing Date: " + filingDate.year + "/" + filingDate.month + "/" + filingDate.day
                + ", report_type: " + reportType + ", Report url: " + reportUrl + "]";
    }

}

这是用于映射对象的Extractor类:

Here is the Extractor class to map the objects:

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class ExtractorClass {

@SerializedName("filings")
@Expose
private List<Filing> filings = null;
@SerializedName("company")
@Expose
private Company company;
@SerializedName("next_page")
@Expose
private String nextPage;

public List<Filing> getFilings() {
return filings;
}

public void setFilings(List<Filing> filings) {
this.filings = filings;
}

public Company getCompany() {
return company;
}

public void setCompany(Company company) {
this.company = company;
}

public String getNextPage() {
return nextPage;
}

public void setNextPage(String nextPage) {
this.nextPage = nextPage;
}

}

这是主应用程序窗口中的JButton:

Here is the JButton in the main application window:

    JButton btnNewButton = new JButton("Search");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                ApiClient defaultClient = Configuration.getDefaultApiClient();
                ApiKeyAuth auth = (ApiKeyAuth) defaultClient.getAuthentication("ApiKeyAuth");
                auth.setApiKey("API_KEY");

                // String identifier = "AAPL"; // String | A Company identifier (Ticker,
                // CIK, LEI, Intrinio ID)

                String reportType = null; // String | Filter by report type [see -
                // /documentation/sec_filing_report_types]. Separate values with commas to
                // return multiple report types.
                LocalDate startDate = null; // LocalDate | Filed on or after the given date
                LocalDate endDate = null; // LocalDate | Filed before or after the given date
                Integer pageSize = 50; // Integer | The number of results to return
                String nextPage = null; // String | Gets the next page of data from a previous API call

                String userInput = null;

                CompanyApi companyApi = new CompanyApi();
                userInput = textField.getText().trim().toUpperCase();
                String identifier = userInput;

                try {

                    ApiResponseCompanyFilings result = companyApi.getCompanyFilings(identifier, reportType, startDate,
                            endDate, pageSize, nextPage);

                    String convertedResult = new Gson().toJson(result);

                    ExtractorClass extractedObjects = new Gson().fromJson(convertedResult, ExtractorClass.class);
                    model.addFilings(extractedObjects);

                } catch (ApiException e) {
                    System.err.println("Exception when calling CompanyApi#getCompanyFilings");
                    e.printStackTrace();
                }
            }

        });

最后是定制表:

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

import javax.swing.table.AbstractTableModel;

import com.g4ther.SECextractor.Date;
import com.g4ther.SECextractor.Filing;
import com.g4ther.SECextractor.FilingDate;

public class FilingsTableModel extends AbstractTableModel
{
    private String[] columnNames =
    {
        "ID",
        "Filing Date",
        "Report Type",
        "Report URL"
    };

    private List<Filing> filings;

    public FilingsTableModel()
    {
        filings = new ArrayList<Filing>();
    }

    public FilingsTableModel(List<Filing> filings)
    {
        this.filings = filings;
    }

    public int getColumnCount()
    {
        return columnNames.length;
    }

    public String getColumnName(int column)
    {
        return columnNames[column];
    }

    public int getRowCount()
    {
        return filings.size();
    }

    @Override
    public Class getColumnClass(int column)
    {
        switch (column)
        {
            case 2: return Date.class;
            default: return String.class;
        }
    }

    @Override
    public boolean isCellEditable(int row, int column)
    {
        switch (column)
        {
            case 2: return true; // only the birth date is editable
            default: return false;
        }
    }

    @Override
    public Object getValueAt(int row, int column)
    {
        Filing filing = getFiling(row);

        switch (column)
        {
            case 0: return filing.getId();
            case 1: return filing.getFilingDate();
            case 2: return filing.getReportType();
            case 3: return filing.getReportUrl();
            default: return null;
        }
    }

    @Override
    public void setValueAt(Object value, int row, int column)
    {
        Filing filing = getFiling(row);

        switch (column)
        {
            case 0: ((Filing) filing).setId((String)value); break;
            case 1: ((Filing) filing).setFilingDate((FilingDate)value); break;
            case 2: ((Filing) filing).setReportType((String)value); break;
            case 3: ((Filing) filing).setReportUrl((String)value); break;
        }

        fireTableCellUpdated(row, column);
    }

    public Filing getFiling(int row)
    {
        return filings.get( row );
    }

    public void addFilings(Filing filing)
    {
        insertFilings(getRowCount(), filing);
    }

    public void insertFilings(int row, Filing filing)
    {
        filings.add(row, filing);
        fireTableRowsInserted(row, row);
    }


}

原始API响应:

{
    "filings": [
        {
            "id": "fil_95GBZB",
            "filing_date": {
                "year": 2019,
                "month": 10,
                "day": 30
            },
            "accepted_date": {
                "dateTime": {
                    "date": {
                        "year": 2019,
                        "month": 10,
                        "day": 30
                    },
                    "time": {
                        "hour": 16,
                        "minute": 30,
                        "second": 40,
                        "nano": 0
                    }
                },
                "offset": {
                    "totalSeconds": 0
                }
            },
            "period_end_date": {
                "year": 2019,
                "month": 10,
                "day": 30
            },
            "report_type": "8-K",
            "sec_unique_id": "0000320193-19-000117",
            "filing_url": "https://www.sec.gov/Archives/edgar/data/320193/000032019319000117/0000320193-19-000117-index.htm",
            "report_url": "https://www.sec.gov/ix?doc\u003d/Archives/edgar/data/320193/000032019319000117/a8-kq420199282019.htm",
            "instance_url": "https://www.sec.gov/Archives/edgar/data/320193/000032019319000117/aapl-20191030.xsd"
        }
    ],
    "company": {
        "id": "com_NX6GzO",
        "ticker": "AAPL",
        "name": "Apple Inc",
        "lei": "HWUPKR0MPOU8FGXBT394",
        "cik": "0000320193"
    },
    "next_page": "MjAxOS0xMC0zMHw1NzkxNjc1"
}

将其映射并将提取的对象打印到控制台后:

[[id: null, Filing Date: 2019/10/30, report_type: 8-K, Report url: https://www.sec.gov/ix?doc=/Archives/edgar/data/320193/000032019319000117/a8-kq420199282019.htm]]

真的卡在这里了,有人可以帮我吗?

Really stuck here, can anyone help me please?

推荐答案

FilingsTableModel类型的addFilings(Filing)方法不适用于参数(ExtractorClass)

The method addFilings(Filing) in the type FilingsTableModel is not applicable for the arguments (ExtractorClass)

首先,方法名称应为addFiling(...),因为该参数是单个Filing对象.

First of all the method name should be addFiling(...) since the parameter is a single Filing object.

您的提取器类具有以下方法:

Your extractor class has the following method:

public List<Filing> getFilings() 
{
    return filings;
}

哪个返回ListFiling个对象.

因此,您需要遍历List并为List中包含的每个Filing对象调用addFiling(...)方法.

So you need to iterate through the List and invoke the addFiling(...) method for each Filing object contained in the List.

这篇关于将POJO对象放入JTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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