将对象添加到ArrayList的问题

时间:2011-06-22 14:36:43

标签: java user-interface arraylist jtable

我收到一个错误,当我向ArrayList添加一个对象TestData时,gui没有正确显示,这是我的代码:

(错误出现在lstTest.add(new TestData("Jon", 0));

主要课程:

import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import javax.swing.event.*; 
import javax.swing.*;
import java.util.*;
import javax.swing.border.*;
public class Test extends JFrame implements ActionListener, ListSelectionListener
{
    private ArrayList<TestData> lstTest = null;
    private TestData objTest;
    public TestTable panTestTable;
    private ListSelectionModel lsmTest;
    private JButton btnAdd;
    private static final String Command_Add = "Add";

    public Test()
    {
        super("Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        try{  UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); }
        catch (Exception e){  System.out.println("Unable to load Windows look and feel"); }
        setPreferredSize(new Dimension(500, 400));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        JPanel panMain = (JPanel) getContentPane();

        lstTest = new ArrayList<TestData>();
        lstTest.add(new TestData("Jon", 0));
        panTestTable = new TestTable(lstTest);
        lsmTest = panTestTable.tabTest.getSelectionModel();
        lsmTest.addListSelectionListener(this);
        panTestTable.setBorder(new EmptyBorder(1, 1, 1, 1));

        panMain.add(panTestTable, "Center");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }

    public void actionPerformed(ActionEvent e){}

    public void valueChanged(ListSelectionEvent e){}

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

TestTable类:

import java.util.*; 
import javax.swing.table.*; 
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;

public class TestTable extends JPanel
{
    public ArrayList<TestData> lstTestData;
    public JTable tabTest;
    public BillTableModel absTest;
    public JScrollPane scrollTest;

    public TestTable(ArrayList<TestData> lstTest)
    {
        lstTestData = lstTest;
        absTest = new BillTableModel(lstTestData);
        tabTest = new JTable(absTest);

        tabTest.setFillsViewportHeight(true);
        tabTest.setAutoCreateRowSorter(true);
        tabTest.setRowSelectionAllowed(true);
        tabTest.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tabTest.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        tabTest.setPreferredScrollableViewportSize(new Dimension(250, 159));

        scrollTest = new JScrollPane(tabTest);
        scrollTest.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        add(scrollTest);

        setOpaque(true);
    }

    public void SetData(ArrayList<TestData> lstTestData)
    {  
        this.lstTestData = lstTestData;
        absTest.SetData(lstTestData); 
    }
    public int SelectRow()
    {
        return tabTest.getSelectedRow();
    }
    public int GetSelectedRow()
    {
        return tabTest.getSelectedRow();
    }
    public void DeleteSelectedRow()
    {
        try
        {
           lstTestData.remove(tabTest.getSelectedRow());
           SetData(lstTestData);
        }
        catch(Exception ex){}
    }
    public void DeleteAllRows()
    {
         for( int i = absTest.getRowCount() - 1; i >= 0; i-- )
         {
              lstTestData.remove(i);
              SetData(lstTestData);
         }
    }


    public class BillTableModel extends AbstractTableModel
    {  
        protected String[] columnNames = new String[ ] {"Name", "Payment"};
        protected ArrayList<TestData> lstTestData;
        protected Class[] types = new Class[]{String.class, double.class};

        public BillTableModel(ArrayList<TestData> lstTestData)
        {    this.lstTestData = lstTestData;    }

        public void SetData(ArrayList<TestData> lstTestData)
        {    this.lstTestData = lstTestData; fireTableDataChanged();    }

        @Override
        public String getColumnName(int columnIndex)
        {    return columnNames[columnIndex];   }

        @Override
        public Class getColumnClass(int columnIndex)
        {    return types [columnIndex];   }

        @Override
        public boolean isCellEditable(int row, int columnIndex)
        {    if (columnIndex != 1) return false;  else return true;    }

        public Object getValueAt(int row, int column)
        {
            if (row < 0 || row > lstTestData.size()) return null;
            TestData obj = lstTestData.get(row);
            switch(column)
            {
                case 0: return obj.getName();
                case 1: return obj.getPayment();
                default: return null;
            }
        }

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

TestData类:

public class TestData implements Comparable <TestData>
{
    private String name;
    private double payment;

    public TestData(String name, double payment)
    {
        this.name = name;
        this.payment = payment;
    }

    public String getName() {return name;}
    public double getPayment() { return payment; }

    public void setName(String s) {name = s;}
    public void setPayment(double d) { payment = d; }

    @Override
    public int compareTo(TestData obj)
    {
      return name.compareTo(obj.getName());
    }

    @Override
    public boolean equals(Object obj)
    {
         if (obj instanceof TestData == false){ return false;}
         return name.equals(((TestData)obj).getName());
    }

}

你能帮我解决一下这个问题吗?

修改

这是错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.JTable.prepareRenderer(JTable.java:5720)
    at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2072)
    at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1974)
    at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1770)
    at javax.swing.plaf.ComponentUI.update(ComponentUI.java:143)
    at javax.swing.JComponent.paintComponent(JComponent.java:752)
    at javax.swing.JComponent.paint(JComponent.java:1029)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JViewport.paint(JViewport.java:747)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paint(JComponent.java:1038)
    at javax.swing.JLayeredPane.paint(JLayeredPane.java:567)
    at javax.swing.JComponent.paintChildren(JComponent.java:862)
    at javax.swing.JComponent.paintToOffscreen(JComponent.java:5131)
    at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1479)
    at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1410)
    at javax.swing.RepaintManager.paint(RepaintManager.java:1224)
    at javax.swing.JComponent.paint(JComponent.java:1015)
    at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:21)
    at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:60)
    at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:97)
    at java.awt.Container.paint(Container.java:1780)
    at java.awt.Window.paint(Window.java:3375)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:796)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:713)
    at javax.swing.RepaintManager.seqPaintDirtyRegions(RepaintManager.java:693)
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:125)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

EDIT2:

这是我在运行程序时加速的gui:

enter image description here

EDIT3:

,从代码中删除lstTest.add(new TestData("Jon", 0));后,gui没有错误:

enter image description here

3 个答案:

答案 0 :(得分:9)

在BillTableModel中创建Class数组的

,不应该使用原始类型。 使用Double.class而不是double.class。

这可以解决您的问题。

public class BillTableModel extends AbstractTableModel {
    protected String[] columnNames = new String[] { "Name", "Payment" };
    protected ArrayList<TestData> lstTestData;
    protected Class[] types = new Class[] { String.class, Double.class };
    ....
    ....
}

答案 1 :(得分:0)

Dan发现了这个问题,但是您的代码中还有另一个错误:

if (row < 0 || row > lstTestData.size()) return null;

应该是:

if (row < 0 || row >= lstTestData.size()) return null;

答案 2 :(得分:0)

而不是这个

public void DeleteAllRows()
    {
         for( int i = absTest.getRowCount() - 1; i >= 0; i-- )
         {
              lstTestData.remove(i);
              SetData(lstTestData);
         }
    }

只需创建一个空列表并调用SetData。