2

在我一直在处理的程序中,我需要用新数据刷新表。目前,由于我是 GUI 新手,我打算用一个新表刷新整个 GUI。我的程序会这样做,但它最终会在之前的 GUI 下构建。

为了继续这个项目并继续前进直到我可以重建,我想做两件事之一。要么使以前的 GUI 无效并使用新的 GUI,要么编辑表模型。现在,我使用的是 DefaultTableModel,因为我是用 JTable 构建的。三个关键文件是

AppGUI.java

//compile javac -cp ;./jsoup-1.6.3.jar;commons-logging-1.1.1.jar;commons-httpclient-3.0.1.jar;commons-codec-1.6.jar;httpclient-4.2.jar AppGUI.java

public class AppGUI extends JFrame{

public AppGUI(Company company)throws Exception {

        retrieveGUI(company);
}

public void retrieveGUI(Company company){
        this.company = company;
        incomeStatementPane = new IncomeStatementPane();
        balanceSheetPane = new BalanceSheetPane();
        cashFlowsPane = new CashFlowsPane();

        JTabbedPane leftTabbedPane = new JTabbedPane();             //Left Pane
        JComponent panel1 = incomeStatementPane.render(company);            //Income Statement 
        leftTabbedPane.addTab("Income Statement", panel1);
        leftTabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
        JComponent panel2 = balanceSheetPane.render(company);               //Balance Sheet PAnel
        leftTabbedPane.addTab("Balance Sheet", panel2);
        leftTabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
        JComponent panel3 = cashFlowsPane.render(company);                  //Cash Flows Panel
        leftTabbedPane.addTab("Cash Flows", panel3);
        leftTabbedPane.setMnemonicAt(2, KeyEvent.VK_3);

        JTabbedPane rightTabbedPane = new JTabbedPane();            //Right Pane
        JComponent panel4 = LiquidityPane.render(company);                  //Liquidity
        rightTabbedPane.addTab("Liquidity", panel4);
        //ratioTabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
        JComponent panel5 = ProfitabilityPane.render(company);              //Profitability 
        rightTabbedPane.addTab("Profitability", panel5);
        //ratioTabbedPane.setMnemonicAt(4, KeyEvent.VK_5);
        JComponent panel6 = LongTermSolvencyPane.render(company);           //Long Term Solvency
        rightTabbedPane.addTab("Long Term Solvency", panel6);
        //ratioTabbedPane.setMnemonicAt(5, KeyEvent.VK_6);
        JComponent panel7 = CashFlowAdequacyPane.render(company);           //Cash Flow 
        rightTabbedPane.addTab("Cash Flow", panel7);

        add(rightTabbedPane, BorderLayout.CENTER);
        add(leftTabbedPane, BorderLayout.WEST);
        JPanel bottomPanel = new JPanel();
        bottomPanel.setBackground(new Color(150, 150, 150));

        JButton computeBtn = new JButton("Compute Ratios");
        //ActionListener computeBtnListener = new computeListener();        //computebutonlistener
        //computeBtn.addActionListener(computeBtnListener);     //actionlistener

        //compute()
        bottomPanel.add(computeBtn, BorderLayout.EAST);

        JPanel tickerPanel = new JPanel();
        JLabel tickerLabel = new JLabel("Search Ticker:");
        final JTextField tickerField = new JTextField(10);


        JButton searchBtn = new JButton("Search");
        searchBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e){
                final String newTicker = tickerField.getText();
            try{
            refresh(tickerField.getText());
            }
            catch(Exception ae){}
            }
        });



        tickerPanel.add(tickerLabel/*, BorderLayout.WEST*/);
        tickerPanel.add(tickerField/*, BorderLayout.WEST*/);
        tickerPanel.add(searchBtn);
        add(tickerPanel, BorderLayout.NORTH);
        add(bottomPanel, BorderLayout.SOUTH);


}

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

// Enter new symbol.
// compnay 

public void refresh(String newTicker)throws IOException{
Company newCompany = new Company(newTicker);  // Creates new Company. Updating methods are called from constructor automatically.
//System.out.println(newTicker);
//frame.invalidate();
//frame.validate();

retrieveGUI(newCompany);     // Stuff from contstructor.    
}

//public void retrieveNewData(String newTicker){
//Company newCompany = new Company(newTicker);

//}



private Company company;//company from ticker JLabel
private IncomeStatementPane incomeStatementPane;
private BalanceSheetPane balanceSheetPane;
private CashFlowsPane cashFlowsPane;

    public static void main(String[] args) throws Exception{
        Company company = new Company("FTK"); // Creates new Company. Updating methods are called from constructor automatically.
        AppGUI frame = new AppGUI(company); // Creates new App GUI.  Various panes are initialized from constructor.
        frame.retrieveGUI(company);
        frame.setTitle("Financial Calculator | Ratios");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(1000, 500));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

//      public compute(){
//          refresh();
//          render();
//      }

}

公司.java

public class Company {
//Variables and Objects

String Ticker;

private Object[][] incomeStatementInfo = new String[52][11];
private Object[][] balanceSheetInfo = new String [46][11];
private Object[][] cashFlowsInfo = new String [22][11];


Company(){}

Company(String newTicker)throws IOException{
    this.Ticker = newTicker;
    updateCompanyInfo();
}

    //Get Methods
    public Object[][] getIncomeStatementInfo() {
        return incomeStatementInfo;
    }   

    public Object[][] getBalanceSheetInfo(){
        return balanceSheetInfo;
    }
    public Object[][] getCashFlowsInfo(){
        return cashFlowsInfo;
    }

    public void investoolsLogin(){
    HttpClient client = new HttpClient();  

    GetMethod method = new GetMethod("https://online.investools.com/authentication/auth.iedu");  
    client.getParams().setParameter("userid", "d*********");  
    client.getParams().setParameter("password", "S****"); 
    client.getParams().setParameter("http.protocol.single-cookie-header", true);
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    //Updating Methods from Internet or computer
    public void updateCompanyIs()throws IOException{

    File f = new File ("Data/"+(Ticker)+"/IS.txt");
    if(f.exists() == true){


        Scanner input = new Scanner(f);

        while (input.hasNextLine()){    
        for (int row = 0, row_size = incomeStatementInfo[row].length; row < row_size; row++){
                for (int col = 0, col_size = incomeStatementInfo.length; col < col_size; col++){
                    if(input.hasNextLine()){
                    incomeStatementInfo[col][row] = input.nextLine();
                    }
                }
            }           
        }
    }

    if(f.exists() == false){
    //OptionPane.showMessageDialog("Offline Ticker Data Does Not Exist");
        investoolsLogin();

        Document doc = Jsoup.connect("http://toolbox.investools.com/graphs/fundamentalAnalysis.iedu?report=BS&symbol="+(Ticker)).get();

        System.out.println("doc is null: " + (doc == null));
        // Elements table = doc.select("table");
        Elements columns = doc.getElementById("fundamentalsForm").children().select("table").get(0).select("tr").get(0).select("td");
        Iterator<Element> columnIterator = columns.iterator();
        int col = 0;
        int row = 0;
                while (columnIterator.hasNext()) {
                    Element column = columnIterator.next();
                    Elements rows = column.select("table").get(0).select("tr");
                    Iterator<Element> rowsIterator = rows.iterator();
                    col = col + 1;
                    while (rowsIterator.hasNext()){
                    row = row + 1;
                    //Element rowIterator.next = ;
                    incomeStatementInfo[col][row] = rowsIterator.next();
                }
            }
        }
    }   
    public void updateCompanyBs()throws IOException{

    File f = new File ("Data/"+(Ticker)+"/BS.txt");
    if(f.exists() == true){
        //OptionPane.showMessageDialog("Offline Ticker Data Does Not Exist");

        Scanner input = new Scanner(f);
            while (input.hasNextLine()){
            for (int row = 0, row_size = balanceSheetInfo[row].length; row < row_size; row++){
                for (int col = 0, col_size = balanceSheetInfo.length; col < col_size; col++){
                    if(input.hasNextLine()){
                    balanceSheetInfo[col][row] = input.nextLine();
                    }
                }
            }                   
        }
    }   
    if(f.exists() == false){
        investoolsLogin();

        Document doc = Jsoup.connect("http://toolbox.investools.com/graphs/fundamentalAnalysis.iedu?report=BS&symbol="+(Ticker)).get();
            // Elements table = doc.select("table");
        Elements columns = doc.select("fundamentalsForm").first().select("table").get(0).select("tr").get(0).select("td");
        Iterator<Element> columnIterator = columns.iterator();
        int col = 0;
        int row = 0;
                while (columnIterator.hasNext()) {
                    Element column = columnIterator.next();
                    Elements rows = column.select("table").get(0).select("tr");
                    Iterator<Element> rowsIterator = rows.iterator();
                    col = col + 1;
                    while (rowsIterator.hasNext()){
                    row = row + 1;
                    //Element rowIterator.next = ;
                    balanceSheetInfo[col][row] = rowsIterator.next();
                }
            }
        }   
    }
    public void updateCompanyCf()throws IOException{

    File f = new File ("Data/"+(Ticker)+"/CF.txt");
    if(f.exists() == true){
        //OptionPane.showMessageDialog("Offline Ticker Data Does Not Exist");

        Scanner input = new Scanner(f);
        while (input.hasNextLine()){    
                for (int row = 0, row_size = cashFlowsInfo[row].length; row < row_size; row++){
                    for (int col = 0, col_size = cashFlowsInfo.length; col < col_size; col++){
                        if(input.hasNextLine()){
                        cashFlowsInfo[col][row] = input.nextLine();
                        }
                    }
                }                           
            }
        }

    if(f.exists() == false){    
        investoolsLogin();

            Document doc = Jsoup.connect("http://toolbox.investools.com/graphs/fundamentalAnalysis.iedu?report=BS&symbol="+(Ticker)).get();
            // Elements table = doc.select("table");
            Elements columns = doc.getElementById("fundamentalsForm").children().select("table").get(0).select("tr").get(0).select("td");
            Iterator<Element> columnIterator = columns.iterator();
            int col = 0;
            int row = 0;
                while (columnIterator.hasNext()) {
                    Element column = columnIterator.next();
                    Elements rows = column.select("table").get(0).select("tr");
                    Iterator<Element> rowsIterator = rows.iterator();
                    col = col + 1;
                    while (rowsIterator.hasNext()){
                    row = row + 1;
                    //Element rowIterator.next = ;
                    cashFlowsInfo[col][row] = rowsIterator.next();
                }
            }
        }
    }
public void updateCompanyInfo() throws IOException {
        updateCompanyIs();
        updateCompanyBs();
        updateCompanyCf();

}
}

和 IncomeStatePane.java(以及我在其中构建 tablemodel 的类似其他对象类

public class IncomeStatementPane {

public static JComponent render(Company company) {
    // Refreshes all cells
    //Parse HTML for object company
    String[] columnNames = {"","Year","Year", "Year", "Year", "Year","Year","Year", "Year", "Year", "Year"};

    Object[][] is = company.getIncomeStatementInfo();

    JPanel isPanel = new JPanel();
    JTable isTable = new JTable(is, columnNames);
    JScrollPane scrollPane = new JScrollPane(isTable);
    isPanel.add(scrollPane, BorderLayout.CENTER);

    return isPanel;
    }
}

完全可编译的版本是 @ http://dl.dropbox.com/u/43354605/IS.zip

在执行代码搜索时,如何让 AppGUI 无效并重新绘制,或更新表模型。(我知道 GUI 刷新可能并不理想,但我只想继续对版本进行最少的重建)。如果有人有任何见解可以帮助我推动这个项目,那就太好了。PS为了查看第二个gui如何在前一个gui下刷新,您需要最大化窗口。

4

1 回答 1

2

您需要做的就是修改表格的模型。它将触发适当的事件,这将使视图自行刷新。例如,要添加新行:

DefaultTableMode model = (DefaultTableModel) table.getModel();
model.addRow(newRow);

浏览DefaultTableModel 的 javadoc以了解所有可能的操作。并阅读有关 JTable 的教程

于 2012-07-22T22:13:42.080 回答