当前位置: 首页 > 知识库问答 >
问题:

在Jtable中添加JCombobox并在Swing java中获取该行和列

徐柏
2023-03-14

我有一个Jtable,我在其中添加了这样的JComobox。

TableColumn sportColumn = jTable1.getColumnModel().getColumn(2);
        comboBox = new JComboBox();
        comboBox.addItem("Snowboarding");
        comboBox.addItem("Rowing");
        comboBox.addItem("Chasing toddlers");
        comboBox.addItem("Speed reading");
        comboBox.addItem("Teaching high school");
        comboBox.addItem("None");
        sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

我像这样添加了一个jtable的鼠标事件。

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        try {
            int row = jTable1.rowAtPoint(evt.getPoint());
            int col = jTable1.columnAtPoint(evt.getPoint());

            System.out.println("Row" + row + "Column" + col);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

但是当我点击我添加Jcombobox的单元格时,它并没有给出该行和列的放置。我仍然在组合框点击事件中调用了表的点击事件,但它给出了所有时间行0,甚至列0在这里的屏幕截图。

那么,我如何解决它,这样我就可以有行和列?

共有3个答案

景星光
2023-03-14

好吧,这很小,但对我来说很奇怪,但我确实解决了它,但我不认为这是正确的答案,但我解决了它。我调用了。组合按钮操作执行事件,并在其中调用了鼠标单击jtable。用null代替事件。检查一下。

 comboBox.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                jTable1MouseClicked(null);
            }
        });


 private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        try {
            //evt.getPoint();
            System.out.println("row" + jTable1.getSelectedRow());
            System.out.println("col" + jTable1.getSelectedColumn());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }                                    

也许这不是正确的方法,但我解决了这个问题。它正在工作。

最好的解决办法就是

jTable1.getModel().addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                System.out.println("Changed Column"+e.getColumn());
                System.out.println("first row"+e.getFirstRow());
            }
        });

    }
施轶
2023-03-14
table.addMouseListener(new MouseAdapter() 
      {
        @Override
        public void mouseClicked(MouseEvent e) 
        {
            try {
                int rowss = table.rowAtPoint(e.getPoint());
                System.out.println("rowss" + rowss);
                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);
            }
        }
        });

  }

用你的jtbale检查Mouselistner。

更新:在调用printdebugdata()之前添加这两行。

  int rowss = table.rowAtPoint(e.getPoint());
  System.out.println("rowss" + rowss);

我得到了行号,检查我的输出。

输出:

rowss0
Selected: Smith
rowss0
Selected: Smith
rowss1
Selected: Snowboarding
rowss1
Selected: Rowing
rowss1
Selected: Rowing
rowss1
Selected: Rowing
rowss2
Selected: Snowboarding
rowss2
Selected: Snowboarding
rowss2
Selected: Snowboarding
rowss2
Selected: Snowboarding

谢谢..

平学
2023-03-14

依我看,你有三个基本选择...

CellEditorListener附加到DefaultCellEditor监控编辑已停止的事件...

editor.addCellEditorListener(new CellEditorListener() {
    @Override
    public void editingStopped(ChangeEvent e) {
        System.out.println("Editing stopped");
        TableCellEditor editor = (TableCellEditor) e.getSource();
        Object value = editor.getCellEditorValue();
        System.out.println("Selected value = " + value);
    }

    @Override
    public void editingCanceled(ChangeEvent e) {
    }
});

这样做的问题是,实际上无法确定已编辑的单元格。即使引用了JTable,当您收到此事件时,该表已不再处于编辑模式...所以您只知道编辑器的值...

表模型管理器附加到表模型...

model.addTableModelListener(new TableModelListener() {
    @Override
    public void tableChanged(TableModelEvent e) {
        int type = e.getType();
        switch (type) {
            case TableModelEvent.UPDATE:
                if (e.getFirstRow() - e.getLastRow() == 0) {
                    TableModel model = (TableModel) e.getSource();
                    int row = e.getFirstRow();
                    int col = e.getColumn();
                    System.out.println("Update " + row + "x" + col + " = " + model.getValueAt(row, col));
                }
                break;
        }
    }
});

这将让您知道单元格的值何时发生了变化(以及许多其他事情,但这是我们感兴趣的),它不会告诉您的是它为什么发生了变化。

这种方法很好,因为它提供了查找值和单元格所需的所有信息。

只需覆盖TableModelsetValueAt方法并提供您自己的某种通知...

虽然这有点重复了<code>TableModelListener</code>的功能,但您可以设计事件信息,以便它提供更多相关信息,因为<code>TableModelEvent</code>涵盖了许多用户案例。。。

例子

以下是TableRenderDemo的示例,并进行修改以演示前两个概念

import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;

/**
 * TableRenderDemo is just like TableDemo, except that it explicitly initializes
 * column sizes and it uses a combo box as an editor for the Sport column.
 */
public class TableRenderDemo extends JPanel {

    public TableRenderDemo() {
        super(new BorderLayout());

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

        //Set up column sizes.
        initColumnSizes(table);

        //Fiddle with the Sport column's cell editors/renderers.
        setUpSportColumn(table, table.getColumnModel().getColumn(2));

        //Add the scroll pane to this panel.
        add(scrollPane);
    }

    /*
     * This method picks good column sizes.
     * If all column heads are wider than the column's cells'
     * contents, then you can just use column.sizeWidthToFit().
     */
    private void initColumnSizes(JTable table) {
        MyTableModel model = (MyTableModel) table.getModel();
        model.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                int type = e.getType();
                switch (type) {
                    case TableModelEvent.UPDATE:
                        if (e.getFirstRow() - e.getLastRow() == 0) {
                            TableModel model = (TableModel) e.getSource();
                            int row = e.getFirstRow();
                            int col = e.getColumn();
                            System.out.println("Update " + row + "x" + col + " = " + model.getValueAt(row, col));
                        }
                        break;
                }
            }
        });
        TableColumn column = null;
        Component comp = null;
        int headerWidth = 0;
        int cellWidth = 0;
        Object[] longValues = model.longValues;
        TableCellRenderer headerRenderer
                        = table.getTableHeader().getDefaultRenderer();

        for (int i = 0; i < 5; i++) {
            column = table.getColumnModel().getColumn(i);

            comp = headerRenderer.getTableCellRendererComponent(
                            null, column.getHeaderValue(),
                            false, false, 0, 0);
            headerWidth = comp.getPreferredSize().width;

            comp = table.getDefaultRenderer(model.getColumnClass(i)).
                            getTableCellRendererComponent(
                                            table, longValues[i],
                                            false, false, 0, i);
            cellWidth = comp.getPreferredSize().width;

            column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        }
    }

    public void setUpSportColumn(final JTable table,
                    TableColumn sportColumn) {
        //Set up the editor for the sport cells.
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("Snowboarding");
        comboBox.addItem("Rowing");
        comboBox.addItem("Knitting");
        comboBox.addItem("Speed reading");
        comboBox.addItem("Pool");
        comboBox.addItem("None of the above");
        TableCellEditor editor = new DefaultCellEditor(comboBox);
        editor.addCellEditorListener(new CellEditorListener() {

            @Override
            public void editingStopped(ChangeEvent e) {
                System.out.println("Editing stopped");
                TableCellEditor editor = (TableCellEditor) e.getSource();
                Object value = editor.getCellEditorValue();
                System.out.println("Selected value = " + value);
            }

            @Override
            public void editingCanceled(ChangeEvent e) {
            }
        });
        sportColumn.setCellEditor(editor);

        //Set up tool tips for the sport cells.
        DefaultTableCellRenderer renderer
                        = new DefaultTableCellRenderer();
        renderer.setToolTipText("Click for combo box");
        sportColumn.setCellRenderer(renderer);
    }

    class MyTableModel extends AbstractTableModel {

        private String[] columnNames = {"First Name",
            "Last Name",
            "Sport",
            "# of Years",
            "Vegetarian"};
        private Object[][] data = {
            {"Kathy", "Smith",
                "Snowboarding", new Integer(5), new Boolean(false)},
            {"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 final Object[] longValues = {"Jane", "Kathy",
            "None of the above",
            new Integer(20), Boolean.TRUE};

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

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

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

        @Override
        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.
         */
        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

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

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        @Override
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }
    }

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

        //Create and set up the content pane.
        TableRenderDemo newContentPane = new TableRenderDemo();
        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() {
                createAndShowGUI();
            }
        });
    }
}
 类似资料:
  • 我创建了一个表单,其中添加了一个,它有3列。第二列和第三列有编辑器。 我希望当我们选择第二列组合框的第一项时,第三列组合框的第一个组合框也应该被选择,反之亦然。 我该怎么做?

  • 我试图在点击组合框时获取当前行数据。我的问题是,如果我试图在单击组合框时获取详细信息,则检索到的数据是错误的。 这是在集合中填充无效数据。请按照下面提到的确切步骤进行复制。 请运行代码以复制该问题,因为它只在初始选择期间工作,而不是之后。 注意:请仅在第二列中单击“直接” 下面是示例代码:

  • 我正在Java创建一个 代码:

  • 问题内容: 您知道如何将新行添加到吗? 问题答案: 的后面处理表后面的所有数据。为了在表格中添加和删除行,您需要使用 要使用此模型创建表: 要添加一行: 您也可以使用此方法删除行。

  • 我有和我在上编写了以下代码,以从选定项中添加行。 如果用户键入了所需的名称并点击了enter,则必须将其添加到jtable,但它不会添加一行。 我认为事件是原因, 通常我们首先从jComboBox中选择项,然后对 事件(例如JButton)进行编码。 所以在这里,我希望jComboBox中考虑所选项事件被添加到JTable中。 那么对于哪一个事件我必须编写代码或另一种方法来处理呢?