简体   繁体   中英

Having only specific column selectable JTable and/or getting the data from only one column

I have a Swing program with a JTable , and there are two columns: one for names, and one for phone numbers associated with those names. Currently, the program allows for selection of rows, which causes data in both columns to become selected. I want selected data to be output to an array of strings, but only the data from within a certain column (that with phone numbers), no matter how many rows are selected. How would I go about this?

I was thinking of changing setColumnSelectionAllowed(false) to setColumnSelectionAllowed(true) and allowing a JHeader to be clicked to select an entire row, or somehow allowing for getValueAt(int row, int column) to be put into an array and only allow for reading of the phone numbers column.

Code for initializing table:

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

Table is made from CSV file as an array:

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

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