在Jtable Java中创建活动单元获取价值?

时间:2018-10-13 05:03:44

标签: java swing jtable

private void tabelKeyPressed(java.awt.event.KeyEvent evt) {                                 

    int keyCode = evt.getKeyCode();
    if (keyCode == KeyEvent.VK_ENTER) {
        int baris = tabel.getSelectedRow();
        try {
            if (tabel.getValueAt(baris, 0) != null) {
                System.out.println(tabel.getValueAt(baris, 0));
            } else {
                cellEditor.stopCellEditing();
                Robot robot=new Robot();
                robot.keyPress(KeyEvent.VK_TAB);
                robot.keyPress(KeyEvent.VK_TAB);                 

                System.out.println(tabel.getModel().getValueAt(baris, 0));
            }

        } catch (Exception e) {
            System.out.println("Salah");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这是获取所选单元格的值的方法。

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.net.URL;

public class TableWithComboBox extends JPanel implements ActionListener{
    private boolean DEBUG = true;
    JPanel jPanel2;
    JFrame frame;
    JTable table;
    JComboBox comboBox;

    public TableWithComboBox() {
        super(new GridLayout(2, 0));

        table = new JTable(new MyTableModel());
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        // Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        // Add the scroll pane to this panel.

        String[] options = { "Students", "Doctor" };

        comboBox = new JComboBox(options);
        comboBox.setSelectedIndex(0);
        comboBox.addActionListener(this);

        table.addKeyListener(new KeyListener() {

            @Override
            public void keyTyped(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyReleased(KeyEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void keyPressed(KeyEvent evt) {
                // TODO Auto-generated method stub
                int keyCode = evt.getKeyCode();
                if (keyCode == KeyEvent.VK_ENTER) {
                    int row = table.getSelectedRow();
                    int col = table.getSelectedColumns()[0];
                    System.out.println(table.getValueAt(row, col));
                }
            }
        });
        add(comboBox);
        add(scrollPane);

    }

    public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox) e.getSource();
        String optionName = (String) cb.getSelectedItem();
        if (optionName.equals("Doctor")) {
            table.setModel(new MyTableDoctorModel());
        } else {
            table.setModel(new MyTableModel());
        }
    }

    class MyTableDoctorModel extends AbstractTableModel {

        String[] columnNames = { "Name", "Department", "Hospital", "Experience" };

        Object[][] data = { { "Saira", "Dep1", "XYZ", new Integer(3) },
                { "Saira", "Dep1", "XYZ", new Integer(3) },
                { "Saira", "Dep1", "XYZ", new Integer(3) },
                { "Saira", "Dep1", "XYZ", new Integer(3) },

        };

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

        /*
         * JTable uses this method to determine the default renderer/ editor for
         * each cell. If we didn't implement this method, then the last column
         * would contain text ("true"/"false"), rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's editable.
         */
        public boolean isCellEditable(int row, int col) {
            // Note that the data/cell address is constant,
            // no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's data can
         * change.
         */
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                        + " to " + value + " (an instance of "
                        + value.getClass() + ")");
            }

            data[row][col] = value;
            double totalVal = 100.0 + Double.parseDouble(String.valueOf(table
                    .getValueAt(0, 4)));
            fireTableCellUpdated(row, col);

        }

    }

    class MyTableModel extends AbstractTableModel {

        String[] columnNames = { "Name", "Degree", "Board/University",
                "Year of Passing", "CGPA", "Part-Time" };

        Object[][] data = {
                { "Saira", "B.Tech", "VTU", new Integer(2015), new Float(8.33),
                        new Boolean(false) },
                { "Smaira", "B.Sc", "CBSE", new Integer(2007), new Float(7.77),
                        new Boolean(true) },
                { "John", "M.tech", "IIT", new Integer(2009), new Float(8.77),
                        new Boolean(false) },
                { "Jia", "M.Sc", "Thapar", new Integer(2011), new Float(7.21),
                        new Boolean(true) },
                { "Kerry", "B.Com", "DU", new Integer(2014), new Float(8.92),
                        new Boolean(false) }

        };

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

        /*
         * JTable uses this method to determine the default renderer/ editor for
         * each cell. If we didn't implement this method, then the last column
         * would contain text ("true"/"false"), rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's editable.
         */
        public boolean isCellEditable(int row, int col) {
            // Note that the data/cell address is constant,
            // no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's data can
         * change.
         */
        public void setValueAt(Object value, int row, int col) {
            if (DEBUG) {
                System.out.println("Setting value at " + row + "," + col
                        + " to " + value + " (an instance of "
                        + value.getClass() + ")");
            }

            data[row][col] = value;
            double totalVal = 100.0 + Double.parseDouble(String.valueOf(table
                    .getValueAt(0, 4)));

            if (DEBUG) {
                System.out.println("New value of data:");
                printDebugData();
            }
        }

        private void printDebugData() {
            int numRows = getRowCount();
            int numCols = getColumnCount();
            for (int i = 0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j = 0; j < numCols; j++) {
                    System.out.print("  " + data[i][j]);
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private void createAndShowGUI(TableWithComboBox newContentPane) {
        // Create and set up the window.
        frame = new JFrame("TableDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        jPanel2 = new JPanel();

        frame.add(jPanel2);

        // Create and set up the content pane.

        frame.add(newContentPane);
        // newContentPane.setOpaque(true); //content panes must be opaque
        // frame.setContentPane(newContentPane);

        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TableWithComboBox newContentPane = new TableWithComboBox();
                newContentPane.createAndShowGUI(newContentPane);

            }
        });
    }

}

答案 1 :(得分:0)

private void tabelKeyReleased(java.awt.event.KeyEvent evt){

    int keyCode = evt.getKeyCode();
    if (keyCode == KeyEvent.VK_ENTER) {
        int baris = tabel.getSelectedRow();
        try {
            if (keyCode == KeyEvent.VK_ENTER) {
                int row = tabel.getSelectedRow();
                System.out.println(tabel.getValueAt(row, 0));
            }
        } catch (Exception e) {
            System.out.println("Salah");
        }
    }
}