按钮单击,ListSelectionListener和JTable

时间:2015-08-21 18:01:03

标签: java jtable actionlistener listselectionlistener

它显示错误,但我不知道为什么。

单击搜索按钮更新JTable值。然后在选择一行后,它会将所选行的最后一列的值打印到控制台。但如果我再次点击搜索按钮,我会收到错误消息。怎么能解决这个问题?

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;



public class Test extends JFrame {
    Container c;
    public JButton search;
    public JTable table;

    public Test() {
        c= getContentPane();
        c.setLayout(new BorderLayout());

        table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        table.setAutoCreateRowSorter(true);
        JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); 

        search = new JButton("Search");

        c.add(scrollPane, BorderLayout.WEST);
        c.add(search, BorderLayout.EAST);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, scrollPane, search);
        splitPane.setOneTouchExpandable(true);
        splitPane.setResizeWeight(0.7);
        add(splitPane, BorderLayout.CENTER);

        ListenerSearch listenersearch = new ListenerSearch();
        search.addActionListener(listenersearch);
    }


    public class ListenerSearch implements ActionListener{
        public void actionPerformed(ActionEvent e){
            try{
                 String[] columnNames = {"A","B","C","D","E"};

                 Object[][] data = {
                            {"Kathy", "Smith",
                             "Snowboarding", new Integer(5), new Boolean(true)},
                            {"John", "Doe",
                             "Rowing", new Integer(3), new Boolean(true)},
                            {"Sue", "Black",
                             "Knitting", new Integer(2), new Boolean(false)},
                            {"Jane", "White",
                             "Speed reading", new Integer(20), new Boolean(true)},
                            {"Joe", "Brown",
                             "Pool", new Integer(10), new Boolean(false)}
                            };

                 MyTableModel changedtable = new MyTableModel();
                 changedtable.setString(columnNames);
                 changedtable.setObject(data);
                 table.setModel(changedtable);

                 table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
                        public void valueChanged(ListSelectionEvent event) {
                            System.out.println(table.getValueAt(table.getSelectedRow(), 4).toString());
                        }
                    }); 
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public static class MyTableModel extends AbstractTableModel { 
            public String[] columnNames = {"First Name",
                                            "Last Name",
                                            "Sport",
                                            "# of Years",
                                            "Vegetarian"};

            public void setString(String[] columnNameshelfer){
                columnNames=columnNameshelfer;
            }

            public Object[][] data = {
            {"Kathy", "Smith",
             "Snowboarding", new Integer(5), new Boolean(true)},
            {"John", "Doe",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black",
             "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown",
             "Pool", new Integer(10), new Boolean(false)},
            {"Kathy", "Smith",
             "Snowboarding", new Integer(5), new Boolean(true)},
            {"John", "Doe",
             "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black",
             "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown",
             "Pool", new Integer(10), new Boolean(false)}
            };

            public void setObject(Object[][] datahelfer){
                data=datahelfer;
            }

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

            public int getRowCount() {
                return data.length;
            }

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

            public Object getValueAt(int row, int col) {
                return data[row][col];
            }

            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
            }

            public boolean isCellEditable(int row, int col) {
                if (col < 1) {
                    return false;
                } else {
                    return true;
                }
            }

            public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
            }
    }



    public static void main(String[] args) throws Exception {
        Test window = new Test();
        window.setSize(800,400);
        window.setVisible(true);
        window.setTitle("Test");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

错误消息:

java.lang.IndexOutOfBoundsException: Invalid index
at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:514)
at javax.swing.JTable.convertRowIndexToModel(JTable.java:2641)
at javax.swing.JTable.getValueAt(JTable.java:2716)
at Test$ListenerSearch$1.valueChanged(Test.java:74)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:164)
at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:211)
at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:405)
at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:415)
at javax.swing.DefaultListSelectionModel.removeSelectionIntervalImpl(DefaultListSelectionModel.java:576)
at javax.swing.DefaultListSelectionModel.clearSelection(DefaultListSelectionModel.java:420)
at javax.swing.JTable.clearSelection(JTable.java:2116)
at javax.swing.JTable.clearSelectionAndLeadAnchor(JTable.java:2124)
at javax.swing.JTable.tableChanged(JTable.java:4369)
at javax.swing.JTable.setModel(JTable.java:3687)
at Test$ListenerSearch.actionPerformed(Test.java:70)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

1 个答案:

答案 0 :(得分:1)

问题在于此代码行

 System.out.println(table.getValueAt(table.getSelectedRow(), 4).toString());

当未选择行时table.getSelectedRow()等于-1 .so,当您致电时

table.getValueAt(table.getSelectedRow(), 4).toString()

您收到错误,因为行-1和第4列

没有单元格

在获取此类

之前的单元格值之前修复此检查getSelectedRow()
if(table.getSelectedRow()>=0){ // check if a row is selected

       System.out.println(table.getValueAt(table.getSelectedRow(), 4).toString());

}

注意:这将修复你的错误。但我不知道你的程序的逻辑是什么。每次点击搜索按钮时你都会改变模型。对我来说看起来不好但是我不能肯定说直到我知道你的程序应该做什么。