2013-01-19 77 views
0

我的要求是顯示網格中的StockQuote符號(流數據)。 對此已選擇JTableDefaultTableModel setValueAt引發ArrayIndexOutOfboundsException

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Random; 

import javax.swing.JFrame; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.SwingUtilities; 
import javax.swing.Timer; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 
import javax.swing.table.DefaultTableModel; 

public class Preethi { 

    protected void initUI() { 
     final Random random = new Random(); 

     final DefaultTableModel model = new DefaultTableModel(new String[] { "Id", "Name", "Desg", "Sal" }, 0); 
     final JTable table = new JTable(model); 
     table.setFillsViewportHeight(true); 
     JFrame frame = new JFrame(Preethi.class.getSimpleName()); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     JScrollPane scrollpane = new JScrollPane(table); 
     frame.add(scrollpane, BorderLayout.CENTER); 
     frame.pack(); 
     frame.setVisible(true); 

     Random ran = new Random(12); 
     ran.nextFloat(); 

     String str = new String("sss"); 

     String[] socrates = {str, str, str }; 
     model.addRow(socrates); 

     System.out.println(model.getRowCount()); 
     System.out.println(model.getColumnCount()); 

     model.setValueAt(new Object[]{"ewqeq","rtgre","gfdgd","mbmnb"}, 1, 4); 
    } 

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, 
      UnsupportedLookAndFeelException { 
     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new Preethi().initUI(); 
      } 
     }); 
    } 
} 
+3

第一個錯誤:您的Employee類具有靜態變量和靜態getter,但實例設置器。這是沒有意義的。整個擺脫靜態。 –

+0

什麼是問題? – Amarnath

回答

1

您不能設置不存在的行的值。

DefaultTableModeladdRow

正如喬恩提到的,對於您的數據對象

+0

請參閱:http://stackoverflow.com/questions/18282753/firetablerowsupdated-not-work-after-up-date-done-in-jtable – Sajad

1
model.setValueAt(new Object[]{"ewqeq","rtgre","gfdgd","mbmnb"}, 1, 4); 

行,你應該不使用靜態方法和字段可以不存在,所以你會得到ArrayIndexOutOfBoundsException.因此,作爲MadProgrammer建議使用addRow(..)方法並將您的對象傳遞給該方法。

例子:

model.addRow(new Object[]{"ewqeq","rtgre","gfdgd","mbmnb"}); 

UPDATE:

你只定義了4列,以便指數將是從0到3。但你在setValueAt方法給出4。所以你的問題保持不變。將其更改爲3.

+0

謝謝切,我用同樣的setValueAt與1,4。 (在我的程序中),但仍然相同 – Pawan

+0

_SetValueAt_將更新現有的。所以如果該行存在,那麼你可以更新,否則你將無法做到。而_addRow_會將新行添加到現有行。 – Amarnath

+0

看看我的更新。 – Amarnath