我创建了以下 JTable 和一些按钮。其中一个按钮 (jbtClear) 正在尝试使用 setRowCount() 函数清空表格。任何想法,为什么它不起作用并产生此错误?
这是代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nysemarketpick;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
/**
*
* @author Administrator
*/
public class PortfolioForm extends javax.swing.JFrame {
/**
* Creates new form PortfolioForm
*/
public PortfolioForm() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jbtAddRow = new javax.swing.JButton();
jbtDeleteRow = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jbtSave = new javax.swing.JButton();
jbtClear = new javax.swing.JButton();
jbtRestore = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Row functions"));
jbtAddRow.setText("Add New Row");
jbtDeleteRow.setText("Delete Selected Row");
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(34, 34, 34)
.add(jbtAddRow))
.add(jPanel1Layout.createSequentialGroup()
.add(16, 16, 16)
.add(jbtDeleteRow)))
.addContainerGap(40, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jbtAddRow)
.add(18, 18, 18)
.add(jbtDeleteRow)
.addContainerGap(26, Short.MAX_VALUE))
);
jTable1.setAutoCreateRowSorter(true);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Stock Symbol", "Stock Name", "Shares", "Value (in Dollars)", "Total Value"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class
};
boolean[] canEdit = new boolean [] {
true, false, true, true, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tableModel = (DefaultTableModel)jTable1.getModel();
jTable1.setColumnSelectionAllowed(true);
jTable1.setRowSelectionAllowed(true);
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jTable1);
jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
//add action listeners
jbtAddRow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (jTable1.getSelectedRow() >= 0)
tableModel.insertRow(jTable1.getSelectedRow(), new Vector());
else
tableModel.addRow(new Vector());
}
});
jbtDeleteRow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (jTable1.getSelectedRow() >= 0)
tableModel.removeRow(jTable1.getSelectedRow());
}
});
jbtSave.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("portfolio.dat"));
out.writeObject(tableModel.getDataVector());
out.writeObject(getColumnNames());
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jbtClear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
tableModel.setRowCount(0);
}
});
jbtRestore.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("portfolio.dat"));
Vector rowData = (Vector)in.readObject();
Vector columnNames = (Vector)in.readObject();
tableModel.setDataVector(rowData, columnNames);
in.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
//add other listeners
tableModel.addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent e)
{
DefaultTableModel model = (DefaultTableModel)e.getSource();
//Object data = model.getValueAt(e.getFirstRow(), e.getColumn());
if (e.getColumn() == 0)
{
Object data = model.getValueAt(e.getFirstRow(), e.getColumn());
String stockSymbol = (String)data;
XMLService2 myService = new XMLService2(stockSymbol);
String stockName = XMLService2.getStockName();
model.setValueAt(stockName, e.getFirstRow(), e.getColumn() + 1);
}
if (e.getColumn() != 4 && model.getValueAt(e.getFirstRow(), 2) != null && model.getValueAt(e.getFirstRow(), 3) != null)
{
Double myDouble =(Integer)model.getValueAt(e.getFirstRow(), 2)*(Double)model.getValueAt(e.getFirstRow(), 3);
model.setValueAt(myDouble, e.getFirstRow(), 4);
}
}
});
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Table functions"));
jbtSave.setText("Save");
jbtClear.setText("Clear");
jbtRestore.setText("Restore");
org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.add(34, 34, 34)
.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jbtRestore)
.add(jbtClear)
.add(jbtSave))
.addContainerGap(41, Short.MAX_VALUE))
);
jPanel2Layout.linkSize(new java.awt.Component[] {jbtClear, jbtRestore, jbtSave}, org.jdesktop.layout.GroupLayout.HORIZONTAL);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.add(jbtSave)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jbtClear)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jbtRestore))
);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(21, 21, 21)
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 645, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(31, 31, 31)
.add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(78, 78, 78)
.add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(50, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 399, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(27, 27, 27)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PortfolioForm().setVisible(true);
}
});
}
//---other methods
private Vector getColumnNames()
{
Vector<String> columnNames = new Vector<String>();
for (int i = 0; i < jTable1.getColumnCount(); i++)
columnNames.add(jTable1.getColumnName(i));
return columnNames;
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private DefaultTableModel tableModel;
private javax.swing.JButton jbtAddRow;
private javax.swing.JButton jbtClear;
private javax.swing.JButton jbtDeleteRow;
private javax.swing.JButton jbtRestore;
private javax.swing.JButton jbtSave;
// End of variables declaration
}
后期编辑:这是来自具有相同功能的书中的工作代码:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projecttable5;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
/**
*
* @author Administrator
*/
public class ModifyTable extends JFrame{
//Create table column names
private String[] columnNames = {"Country", "Capital", "Population in Millions", "Democracy"};
//Create table data
private Object[][] rowData = {
{"USA", "Washington DC", 280, true},
{"Canada", "Ottawa", 32, true},
{"United Kingdom", "London", 60, true},
{"Germany", "Berlin", 83, true},
{"France", "Paris", 60, true},
{"Norway", "Oslo", 4.5, true},
{"India", "New Delhi", 1046, true}
};
//Create a table model
private DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames);
//Create a table
private JTable jTable1 = new JTable(tableModel);
//Create buttons
private JButton jbtAddRow = new JButton("Add New Row");
private JButton jbtAddColumn = new JButton("Add New Column");
private JButton jbtDeleteRow = new JButton("Delete Selected Row");
private JButton jbtDeleteColumn = new JButton("Delete Selected Column");
private JButton jbtSave = new JButton("Save");
private JButton jbtClear = new JButton("Clear");
private JButton jbtRestore = new JButton("Restore");
//Create a combo box for selection modes
private JComboBox jcboSelectionMode = new JComboBox(new String[] {"SINGLE_SELECTION", "SINGLE_INTERVAL_SELECTION", "MULTIPLE_INTERVAL_SELECTION"});
//Create check boxes
private JCheckBox jchkRowSelectionAllowed = new JCheckBox("RowSelectionAllowed", true);
private JCheckBox jchkColumnSelectionAllowed = new JCheckBox("ColumnSelectionAllowed", false);
//---Default constructor
public ModifyTable()
{
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(2, 2));
panel1.add(jbtAddRow);
panel1.add(jbtAddColumn);
panel1.add(jbtDeleteRow);
panel1.add(jbtDeleteColumn);
JPanel panel2 = new JPanel();
panel2.add(jbtSave);
panel2.add(jbtClear);
panel2.add(jbtRestore);
JPanel panel3 = new JPanel();
panel3.setLayout(new BorderLayout(5, 0));
panel3.add(new JLabel("Selection Mode"), BorderLayout.WEST);
panel3.add(jcboSelectionMode, BorderLayout.CENTER);
JPanel panel4 = new JPanel();
panel4.setLayout(new FlowLayout(FlowLayout.LEFT));
panel4.add(jchkRowSelectionAllowed);
panel4.add(jchkColumnSelectionAllowed);
//Gather panel3 and panel4
JPanel panel5 = new JPanel();
panel5.setLayout(new GridLayout(2, 1));
panel5.add(panel3);
panel5.add(panel4);
//Gather panel1 and panel2
JPanel panel6 = new JPanel();
panel6.setLayout(new BorderLayout());
panel6.add(panel1, BorderLayout.SOUTH);
panel6.add(panel2, BorderLayout.CENTER);
add(panel5, BorderLayout.NORTH);
add(new JScrollPane(jTable1), BorderLayout.CENTER);
add(panel6, BorderLayout.SOUTH);
//Initialize table selection mode
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Add listeners
jbtAddRow.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedRow() >= 0)
tableModel.insertRow(jTable1.getSelectedRow(), new Vector());
else
tableModel.addRow(new Vector());
}
});
jbtAddColumn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String name = JOptionPane.showInputDialog("New Column Name");
tableModel.addColumn(name, new Vector());
}
});
jbtDeleteRow.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedRow() >= 0)
tableModel.removeRow(jTable1.getSelectedRow());
}
});
jbtDeleteColumn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if (jTable1.getSelectedColumn() >= 0)
{
TableColumnModel columnModel = jTable1.getColumnModel();
TableColumn tableColumn = columnModel.getColumn(jTable1.getSelectedColumn());
columnModel.removeColumn(tableColumn);
}
}
});
jbtSave.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablemodel.dat"));
out.writeObject(tableModel.getDataVector());
out.writeObject(getColumnNames());
out.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jbtClear.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
tableModel.setRowCount(0);
}
});
jbtRestore.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablemodel.dat"));
Vector rowData = (Vector)in.readObject();
Vector columnNames = (Vector)in.readObject();
tableModel.setDataVector(rowData, columnNames);
in.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
jchkRowSelectionAllowed.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
jTable1.setRowSelectionAllowed(jchkRowSelectionAllowed.isSelected());
}
});
jchkColumnSelectionAllowed.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
jTable1.setColumnSelectionAllowed(jchkColumnSelectionAllowed.isSelected());
}
});
jcboSelectionMode.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String selectedItem = (String)jcboSelectionMode.getSelectedItem();
if (selectedItem.equals("SINGLE_SELECTION"))
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
else if (selectedItem.equals("SINGLE_INTERVAL_SELECTION"))
jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
else if (selectedItem.equals("MULTIPLE_INTERVAL_SELECTION"))
jTable1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
});
}//end of default constructor
private Vector getColumnNames()
{
Vector<String> theColumnNames = new Vector<>();
for (int i = 0; i < jTable1.getColumnCount(); i++)
theColumnNames.add(jTable1.getColumnName(i));
return theColumnNames;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try
{
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
}
catch(Exception e)
{
}
ModifyTable frame = new ModifyTable();
frame.setLocationRelativeTo(null); //Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("TableSortFilter");
frame.pack();
//frame.setSize(new Dimension(300, 300));
frame.setVisible(true);
}
}