【问题标题】:Get selected row of JTable when itemStateChanged in JComboBox当JComboBox中的itemStateChanged时获取JTable的选定行
【发布时间】:2018-08-10 09:29:47
【问题描述】:

我试图在单击组合框时获取当前行数据。 我的问题是,如果我尝试在单击组合框时获取详细信息,则检索到的数据是错误的。

这是在集合中填充无效数据。请按照下面提到的确切步骤进行复制。

请运行代码以复制问题,因为它仅在初始选择期间有效,但在之后无效。

注意:请仅在第二列上直接点击

Step 1: Click on Second Column of Row 1
Step 2: Select- Item 1 
Step 3: Click on Second Column of Row 2
Step 4: Select- Item 2
Step 5: Click on Second Column of Row 3
Step 6: Select- Item 3
WORKS Fine till here :)
Step 7 : Click on Second column of Row 1 and do not change an selection leave it as it is (Just click on the combobox twice)
Step 8 : Click on Second column of Row 2, DO NO CHANGES
Step 9 : Click on Second column of Row 3, DO NO CHANGES
Step 10: NOW randomly click on any of the second columns of rows(1,2,3) and see the output datamap. It really wierd why the event is

下面是示例代码:

import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TestJCombo extends JFrame {

    public TestJCombo() {
        initialize();
    }

    JTable jTable;
    JComboBox comboBox;
    Map<Integer, String> dataMap;

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(50000, 25);
        field.setText("                                                                                           ");

        jTable = new JTable();

        comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item 1");
        comboBox.addItem("item 2");
        comboBox.addItem("item 3");
        comboBox.setEditable(false);

        dataMap = new LinkedHashMap();

        comboBox.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {

                    Object selected = comboBox.getSelectedItem();

                    int selectedRow = jTable.getSelectedRow();
                    selectedRow = jTable.convertRowIndexToModel(selectedRow);
                    if (selectedRow != -1) {
                        String user = (String) jTable.getValueAt(selectedRow, 0);
                        String data = "Row: " + (selectedRow + 1) + " :::: " + user + " , "
                                + comboBox.getSelectedItem();
                        dataMap.put(selectedRow + 1, "[" + user + " - " + comboBox.getSelectedItem() + "]");
                        if (selected != null) {
                            field.setText(data);
                        }
                        System.out.println("Current data map:: " + dataMap);
                    }
                }

            }
        });

        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable.setRowHeight(30);
        jTable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        DefaultTableModel myTableMdl = new DefaultTableModel();
        myTableMdl.addColumn("User");
        myTableMdl.addColumn("Role");
        jTable.setModel(myTableMdl);

        jTable.getColumn("Role").setCellEditor(new DefaultCellEditor(comboBox));

        Vector tableData;
        for (int i = 1; i <= 7; i++) {
            tableData = new Vector();
            tableData.add("User " + i);
            myTableMdl.addRow(tableData);
        }

        getContentPane().add(jTable);
        getContentPane().add(field);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestJCombo().setVisible(true);
            }
        });
    }
}

【问题讨论】:

  • JTable.getValueAt 方法采用视图索引,而不是模型索引。在您使用此方法之前,您正在将视图索引转换为模型索引,并在该调用中使用模型索引。

标签: java swing jtable jcombobox


【解决方案1】:

问题是您在错误的组件上使用了错误的侦听器。您不应该向组合框添加侦听器。使用编辑器的目的是编辑数据并更新TableModel。您不应引用组合框进行进一步处理。

因此,您应该将TableModelListener 添加到TableModel。然后,只要第 2 列中的值发生更改,就会生成 TableModelEventTableModelEvent 将包含已更改单元格的行/列信息。

您可以查看:JTable -> TableModeListener,了解使用 TableModelListener 的基本示例。在您的情况下,您检查第二列是否更改,然后更新您的地图。

另请注意,您错误地使用了 convertRowIndexToModel() 方法:

selectedRow = jTable.convertRowIndexToModel(selectedRow);
...
    String user = (String) jTable.getValueAt(selectedRow, 0);

首先,如果表格视图被排序或过滤,您只需要担心隐藏行索引。在提供的代码中,您不这样做,因此无需转换索引。

但是,如果您曾经过滤过视图,那么您需要将视图行转换为模型行,然后您必须从模型而不是视图访问数据。所以代码是:

String user = (String) jTable.getModel().getValueAt(selectedRow, 0);

【讨论】:

  • 按照建议,我删除了代码“selectedRow = jTable.convertRowIndexToModel(selectedRow);”谢谢..但是@M给出的解决方案。 Al Jumaily 与添加的双重动作检查完美配合 - -
  • @Anonymous, the solution given by Jumaily works perfectly - 这不是工作的问题,而是使用适当的类来完成工作的问题。您绝不需要扩展 JTable 来获得所需的功能。您不会对房子周围的每项工作都使用“锤子”。您使用正确的工具。有人为您编写代码这一事实并不意味着您应该使用该代码。通过按照设计使用的方式使用类来学习有效地使用 Java。在任何情况下,不要忘记通过单击复选标记“接受”答案,以便人们知道问题已经解决。
  • TableModelListener 是一个很好的方法,它也可以正常工作。谢谢
【解决方案2】:

问题是您正在创建一个JComboBox,然后将其放在列中的所有单元格上。您引用的是JComboBox,而不是为每个单元格创建一个新单元格。这就是为什么当你按照你提到的10个步骤时,得到的结果是非常愚蠢和毫无意义的。

这是解决方法,为第 1 列(角色列)中的所有单元格创建自定义 TableCellEditor。目标是为每个单元创建一个全新的JComboBox。这是通过将JTable 的声明更改为jtable = new JTable(){...}; 以覆盖getCellEditor(...){...} 方法来实现的。此外,private JComboBox createComboBox() {...} 方法是您创建全新 JComboBox 所需要的。

现在,我们将取出addItemListener 并将其替换为addActionListener。这是必需的,因为如果用户选择了已选择的项目,则不会调用 ItemListener 中的 itemStateChanged。我们需要在某种程度上复制两次鼠标单击,一次用于显示下拉列表,第二次用于选择项目(如果不需要,您可以跳过此步骤)。

我还编辑了您的代码,使其更具可读性和效率。

这是一个 MVCE:

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

import javax.swing.table.TableCellEditor;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.BoxLayout;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TestJCombo extends JFrame {

    JTable jTable;
    //JComboBox comboBox;//not needed, replaced by the createComboBox() method.
    Map<Integer, String> dataMap;
    final JTextField FIELD = new JTextField(25);//must put this globally.
    //Since it is final, it should be all in upper case

    //It is a good practice to put the global variables on top and constructor(s) below.
    public TestJCombo() {
        initialize();
    }

    private void initialize() {
        //use pack(); instead setSize(...); I used it at the end of this method.
        //setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        //both lines not needed, it has been taken care of when FIELD was declared.
        //FIELD.setSize(50000, 25);
        //FIELD.setText("                                         "
        //  + "                                                  ");

        //Must create a seperate TableCellEditor for each cell in the table.
        jTable = new JTable() {
            public TableCellEditor getCellEditor(int row, int column) {
                int modelColumn = convertColumnIndexToModel(column);
                //if the cell lies in the second column, create a custom cell editor.
                if (modelColumn == 1) {
                    return (TableCellEditor) new DefaultCellEditor(createComboBox());
                } else {
                    return super.getCellEditor(row, column);
                }
            }
        };

        //comboBox = new JComboBox();
        //comboBox.setEditable(true);
        //comboBox.addItem("item 1");
        //comboBox.addItem("item 2");
        //comboBox.addItem("item 3");
        //comboBox.setEditable(false);
        dataMap = new LinkedHashMap();

        jTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable.setRowHeight(30);
        jTable.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        DefaultTableModel myTableMdl = new DefaultTableModel();
        myTableMdl.addColumn("User");
        myTableMdl.addColumn("Role");
        jTable.setModel(myTableMdl);

        //we have our own custom CellEditor, this is not needed
        //jTable.getColumn("Role").setCellEditor(new DefaultCellEditor(comboBox));
        Vector tableData;
        for (int i = 1; i <= 7; i++) {
            tableData = new Vector();
            tableData.add("User " + i);
            myTableMdl.addRow(tableData);
        }

        //It is better practice to add everything to a 
        //panel and then add that panel to the frame.
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        panel.add(jTable);
        panel.add(Box.createRigidArea(new Dimension(0, 10)));//add some space
        panel.add(FIELD);
        getContentPane().add(panel, BorderLayout.CENTER);
        pack();//should use this.
    }

    private JComboBox createComboBox() {
        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item 1");
        comboBox.addItem("item 2");
        comboBox.addItem("item 3");
        comboBox.setEditable(false);

        //Add an ActionListener so that it would also detect if the user selects
        //the same item. The itemStateChanged in the ItemListener will not be
        //invoked if the user selects the item that is already selected.
        comboBox.addActionListener(new ActionListener() {
            //To update the result everytime the user selects an item
            //(regardless if it was selected or not), we need to "mock"
            //a two-click operation. The first click will show the 
            //drop-down list to select from and the second will
            //allow the user to select the desired choice to be selected.
            boolean doubleClick = false;

            @Override
            public void actionPerformed(ActionEvent ae) {
                if (doubleClick) {
                    int selectedRow = jTable.getSelectedRow();
                    selectedRow = jTable.convertRowIndexToModel(selectedRow);
                    Object selected = comboBox.getSelectedItem();
                    if (selectedRow != -1 && selected != null) {
                        String user = (String) jTable.getValueAt(selectedRow, 0);
                        String data = "Row: " + (selectedRow + 1) + " :::: " + user + " , "
                            + comboBox.getSelectedItem();
                        dataMap.put(selectedRow + 1, "[" + user + " - "
                            + comboBox.getSelectedItem() + "]");
                        FIELD.setText(data);
                        System.out.println("Current data map:: " + dataMap);
                    }
                    doubleClick = false;
                }
                doubleClick = true;
            }
        });

//      comboBox.addItemListener(new ItemListener() {
//
//          public void itemStateChanged(ItemEvent e) {
//              if (e.getStateChange() == ItemEvent.SELECTED) {
//
//                  Object selected = comboBox.getSelectedItem();
//
//                  int selectedRow = jTable.getSelectedRow();
//                  selectedRow = jTable.convertRowIndexToModel(selectedRow);
//                  if (selectedRow != -1) {
//                      String user = (String) jTable.getValueAt(selectedRow, 0);
//                      String data = "Row: " + (selectedRow + 1) + " :::: " + user + " , "
//                          + comboBox.getSelectedItem();
//                      dataMap.put(selectedRow + 1, "[" + user + " - "
//                      + comboBox.getSelectedItem() + "]");
//                      if (selected != null) {
//                          FIELD.setText(data);
//                      }
//                      System.out.println("Current data map:: " + dataMap);
//                  }
//              }
//
//          }
//      });
        return comboBox;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TestJCombo().setVisible(true);
            }
        });
    }
}

【讨论】:

  • 这个解决方案终于奏效了我已经实施了你的建议,而且效果很好。添加的双重操作执行检查也有帮助...谢谢
  • (1-) 虽然这可能有效,但这不是解决问题的方法。组合框的ActionListnerJTable 用于在选择值时更新TableModel。如果您想知道数据何时更改,请使用TableModelListener 来实现您的自定义逻辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-14
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 2012-02-11
相关资源
最近更新 更多