Jtable选择行和列

时间:2014-01-31 17:29:48

标签: java swing jtable

我想选择jtable单元格的行和列并打印该值,我在public void changeValue()中执行此操作,如下所示,但我收到此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at java.util.Vector.elementData(Unknown Source) at java.util.Vector.elementAt(Unknown Source) at javax.swing.table.DefaultTableModel.getValueAt(Unknown Source) at javax.swing.JTable.getValueAt(Unknown Source) at ShopManagement.ShowEmployee.changeValue(ShowEmployee.java:81) at ShopManagement.ShowEmployee.<init>(ShowEmployee.java:74) at ShopManagement.ShowEmployee.main(ShowEmployee.java:87)

也许,让我实现一个用于检查jtable中光标当前位置的mouselistener?

如果是这样,我该如何更改代码?

import java.awt.*;
import java.sql.*;
import java.util.*;

import javax.swing.*;

import DataBaseConnectionSingleton.Connection;
import DataBaseConnectionSingleton.CreationStatement;

public class ShowEmployee extends JFrame {
public JTable table = new JTable();

public ShowEmployee() {
Vector<String> columnNames = new Vector<String>();
Vector<Vector<Object>> data = new Vector<Vector<Object>>();

try {

    Connection.getConnectionInstance();
    Statement st = CreationStatement.getCreationStatementInstance();
    ResultSet rs = st.executeQuery("select * from employee");
    ResultSetMetaData md = rs.getMetaData();
    int columns = md.getColumnCount();

    // Get column names

    for (int i = 1; i <= columns; i++) {
        columnNames.addElement(md.getColumnName(i));
    }

    // Get row data

    while (rs.next()) {
        Vector<Object> row = new Vector<Object>(columns);

        for (int i = 1; i <= columns; i++) {
            row.addElement(rs.getObject(i));
        }

        data.addElement(row);
    }
} catch (Exception e) {
    System.out.println(e);
}

// Create table with database data

table = new JTable(data, columnNames) {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public Class<?> getColumnClass(int column) {
        for (int row = 0; row < getRowCount(); row++) {
            Object o = getValueAt(row, column);

            if (o != null) {
                return o.getClass();
            }
        }

        return Object.class;
    }
};

JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);

JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
changeValue();
}

public void changeValue() {

int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();
String s=(String) table.getValueAt(rowIndex,colIndex);
System.out.println("INNERTABLE:" + rowIndex + "*" + colIndex+" "+s);

}

public static void main(String[] args) {
ShowEmployee frame = new ShowEmployee();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

提前感谢。

2 个答案:

答案 0 :(得分:0)

当您在表单加载本身上调用changeValue()时,它总是将rowIndx和columnIndex作为-1,因为在表单加载时没有选择任何内容。

您可以使用JButton's ActionListener方法执行此操作。由于您要打印所选数据,只需添加名为button的{​​{1}}。您可以在print按钮上使用ActionListener。

看看这个例子

print

输出:

output

public class TableValuePrint extends JFrame implements ActionListener{
    private final JButton print;
    private final JTable table;

    public TableValuePrint() {

        String[] columnNames = {"A", "B", "C"};
        Object[][] data = {
            {"Moni", "adsad", "Pass"},
            {"Jhon", "ewrewr", "Fail"},
            {"Max", "zxczxc", "Pass"}
        };

        table = new JTable(data, columnNames);
        JScrollPane tableSP = new JScrollPane(table);
        JPanel tablePanel = new JPanel();
        tablePanel.add(tableSP);
        tablePanel.setBackground(Color.red);
        add(tablePanel);
        setTitle("Result");

        setSize(1000,700);

        print=new JButton("Print");  
        JPanel jpi1 = new JPanel();  
        jpi1.add(print);  
        tablePanel.add(jpi1,BorderLayout.SOUTH);      

        print.addActionListener(this);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                TableValuePrint ex = new TableValuePrint();
                ex.setVisible(true);
            }
        });
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
       if(ae.getSource()==print){
         int rowIndex = table.getSelectedRow();
         int colIndex = table.getSelectedColumn();
         String s=(String) table.getValueAt(rowIndex,colIndex);
         System.out.println("INNERTABLE:" + rowIndex + "*" + colIndex+" "+s);
        }
    }
}

答案 1 :(得分:0)

此行String s=(String) table.getValueAt(rowIndex,colIndex);

上有错误

使用我的更新答案您可以在单击特定行的位置获取数据..

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.text.ParseException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class ShowEmployee extends JFrame {

public JTable table = new JTable();

public ShowEmployee()
{
    Vector<String> columnNames = new Vector<>();
    Vector<Vector<Object>> data = new Vector<>();
    Connection cd = null;

    try {
        Class.forName("org.sqlite.JDBC");
        cd = DriverManager.getConnection("jdbc:sqlite:tablename.sqlite");
        PreparedStatement pstmt = (PreparedStatement) cd.prepareStatement("select name from table");
        pstmt.execute();
        ResultSet rs1 = pstmt.getResultSet();

        ResultSetMetaData md = rs1.getMetaData();
        int columns = md.getColumnCount();

        // Get column names

        for (int i = 1; i <= columns; i++) {
            columnNames.addElement(md.getColumnName(i));
        }

        // Get row data

        while (rs1.next()) {
            Vector<Object> row = new Vector<Object>(columns);

            for (int i = 1; i <= columns; i++) {
                row.addElement(rs1.getObject(i));
            }

            data.addElement(row);
        }
    } catch (Exception e) {
        System.out.println(e);
    }


    table = new JTable(data, columnNames) {


        private static final long serialVersionUID = 1L;

        @Override
        public Class<?> getColumnClass(int column) {
            for (int row = 0; row < getRowCount(); row++) {
                Object o = getValueAt(row, column);

                if (o != null) {
                    return o.getClass();
                }
            }

            return Object.class;
        }
    };

    JScrollPane scrollPane = new JScrollPane(table);
    getContentPane().add(scrollPane);

    JPanel buttonPanel = new JPanel();
    getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    //changeValue();

    table.addMouseListener(new MouseAdapter() 
      {
        @Override
        public void mouseClicked(MouseEvent e) 
        {
            try {
                printDebugData(table);
            } catch (ParseException ex) {
                Logger.getLogger(ShowEmployee.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        private void printDebugData(JTable jTable1) throws ParseException
        {
              String selectedData = null;

            int numRows = jTable1.getRowCount();
            int numCols = jTable1.getColumnCount();
            int[] selectedRow = jTable1.getSelectedRows();
            int[] selectedColumns = jTable1.getSelectedColumns();
            javax.swing.table.TableModel model = jTable1.getModel();
            for (int i = 0; i < selectedRow.length; i++)
            {
                for (int j = 0; j < selectedColumns.length; j++) 
                {
                    selectedData = (String) jTable1.getValueAt(selectedRow[i], selectedColumns[j]);
                }
                System.out.println("Selected: " + selectedData);
            }
        }
        });

  }


public static void main(String[] args) {
    ShowEmployee frame = new ShowEmployee();
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
 }

谢谢..