简体   繁体   中英

Jtable Select row and columns

I want to select a row and column of jtable's cell and print the value, i do this in public void changeValue() ,as shown below, but i got this error:

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.(ShowEmployee.java:74) at ShopManagement.ShowEmployee.main(ShowEmployee.java:87)`

maybe,have i to implement a mouselistener that is used to check the current position of cursor in jtable?

if so,how can I change the code?

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);
}
}

thanks in advance.

As you are calling the changeValue() on form load itself and it always gives you rowIndx and columnIndex as -1 because nothing is selected on form load.

You can do it using JButton's ActionListener method. As you want to print the selected data just add a button called print .You can use ActionListener on print button.

Look at this example

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);
        }
    }
}

OUTPUT :

产量

INNERTABLE:0*1 adsad
INNERTABLE:2*2 Pass
INNERTABLE:1*1 ewrewr
INNERTABLE:2*0 Max

you have Error on this line String s=(String) table.getValueAt(rowIndex,colIndex);

USE my Update Answer You can get data where you click on perticular row..

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);
}
 }

Thanks..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM