仅具有特定的列可选JTable和/或仅从一列获取数据

问题描述 投票:0回答:1

我有一个带有SwingJTable程序,有两列:一列用于名称,一列用于与这些名称关联的电话号码。当前,该程序允许选择行,这将导致两列中的数据都被选中。我希望将选定的数据输出到字符串数组,但是无论选定多少行,都只输出特定列(带有电话号码)中的数据。我将如何处理?

我曾考虑将setColumnSelectionAllowed(false)更改为setColumnSelectionAllowed(true),并允许单击JHeader以选择整行,或者以某种方式允许将getValueAt(int row, int column)放入数组中,仅允许读取手机数字列。

初始化表的代码:

        // Initializing the JTable
        String[] columns = {"Student", "Phone"};
        students = new JTable(data, columns);
        students.setGridColor(Color.lightGray);
        students.setPreferredScrollableViewportSize(new Dimension(500, 400));
        TableColumnModel columnModel = students.getColumnModel();
        columnModel.getColumn(0).setPreferredWidth(100);
        columnModel.getColumn(1).setPreferredWidth(100);
        students.setRowHeight(25);
        students.setFillsViewportHeight(true);
        students.setRowSelectionAllowed(true);
        students.setColumnSelectionAllowed(false);
        students.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

表是由CSV文件制成的数组:

        String[][] myNewArray1 = new String[30][30]; //creates an array
        Scanner myScanner1 = new Scanner(filePath1); //creates a scanner which uses the text file
        int k = 0;
        while (myScanner1.hasNext()) {
            myNewArray1[k] = myScanner1.nextLine().split(",");
            k++;
        }
        return (myNewArray1);
    }

    // Driver method
    public static void main(String[] args) throws Exception {
        File filePath1 = new File("C:\\Users\\cmorl\\IdeaProjects\\CompSciIA\\src\\CompSciIA.csv"); //file path
        String[][] data1;
        data1 = makeArrayFromTxt(filePath1);
        new Database(data1);
    }
java arrays swing jtable
1个回答
0
投票
 TableModel model =  table.getModel();    
  List <String> data = new ArrayList();
  for (int count = 0; count < model.getRowCount(); count++){
                  data.add(model.getValueAt(count, 0).toString()); //Change 0 with 1 if you want column 2
   }
© www.soinside.com 2019 - 2024. All rights reserved.