dimanche 19 avril 2020

How to get values from rows that contain a checked checkbox?

I am trying to select a row/multiple rows with checkboxes in JTable and I am having trouble when it comes to getting the value of the row,

public class customerFunction extends JFrame {

private static final String DefaultTableModel=null;
private JPanel contentPane;
private JScrollPane scrollPane;


String[] colContent = { "Barcode", "Device Name", "Device Type", "Brand", "Colour", "Connectivity", "Stock","Price", "Additional","Select","JSpinner"};
Object[][] data={ {null,null,null,null,null,null,null,null,null,null}};
DefaultTableModel model = new DefaultTableModel(data, colContent);
JTable table = new JTable(data,colContent);

private static final long serialVersionUID = 1L;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                customerFunction frame = new customerFunction(null);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 * @throws FileNotFoundException 
 */

public customerFunction(String st) throws FileNotFoundException {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 739, 602);
    contentPane = new JPanel();
    contentPane.setBackground(new Color(102, 204, 204));
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel welcomeheader = new JLabel("Welcome" + st + ",");
    welcomeheader.setBounds(10, 11, 187, 26);
    contentPane.add(welcomeheader);

    JLabel choose = new JLabel("All products:");
    choose.setBounds(297, 33, 265, 14);
    contentPane.add(choose);

    JButton paybtn = new JButton("Payment");
    paybtn.setBounds(470, 496, 119, 32);
    contentPane.add(paybtn);

    JButton vbask = new JButton("View Basket");
    vbask.setBounds(470, 453, 119,32);
    contentPane.add(vbask);

    JButton back = new JButton("Back");
    back.setBounds(162, 410, 89, 32);
    contentPane.add(back);

    JLabel fillbl = new JLabel("Filter By:");
    fillbl.setHorizontalAlignment(SwingConstants.TRAILING);
    fillbl.setBounds(456, 72, 106, 14);
    contentPane.add(fillbl);

    scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 101, 701, 279);
    contentPane.add(scrollPane);

    File inputFile = new File("Stock.txt");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    try {
        String firstLine = br.readLine().trim();


        table.getColumn("JSpinner").setCellRenderer(new SpinnerRenderer());
        table.getColumn("JSpinner").setCellEditor(new SpinnerEditor());


        Object[] tableLines = br.lines().toArray();
        model.setRowCount(0);
        for(int i = 0; i < tableLines.length; i++)
        {
            String line = tableLines[i].toString().trim();
            String[] dataRow = line.split(",");
            String bcode = dataRow[0];
            String dname= dataRow[1];
            String dtype = dataRow[2];
            String brand= dataRow[3];
            String colour = dataRow[4];
            String connect= dataRow[5];
            String stock = dataRow[6];
            String price = dataRow[8];
            String addn = dataRow[9];   


            Object rowCont[] = {bcode, dname, dtype, brand, colour, connect, stock, price, addn};
            model.addRow(rowCont);


            }

            table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 6:
                        return Integer.class;
                    case 7:
                        return Integer.class;
                    case 9:
                        return Boolean.class;
                    case 10:
                        return Integer.class;
                    default:
                        return String.class;
                }
            }

            @Override
            public boolean isCellEditable(int row, int col) {
                 switch (col) {
                     case 9:
                         return true;
                     case 10:
                         return true;
                     default:
                         return false;
                  }
            }


        };

        table.setRowSelectionAllowed(true);
        table.setColumnSelectionAllowed(false);

        table.getColumnModel().getColumn(1).setPreferredWidth(100);
        table.getColumnModel().getColumn(2).setPreferredWidth(90);  
        table.getColumnModel().getColumn(5).setPreferredWidth(90);
        table.getColumnModel().getColumn(6).setPreferredWidth(60);
        table.getColumnModel().getColumn(7).setPreferredWidth(50);  
        table.getColumnModel().getColumn(10).setPreferredWidth(105);

This is the action listener for the button that is meant to be clicked to show the data from the checked rows.

        JButton btn=new JButton("Get Selected");
        btn.addActionListener(new ActionListener() {

          @Override
          public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub

            //GET SELECTED ROW
            for(int i=0;i<table.getRowCount();i++)
            {
              Boolean checked=Boolean.valueOf(table.getValueAt(i, 9).toString());
              String col=table.getValueAt(i, 1).toString();

              //DISPLAY
              if(checked)
              {
                JOptionPane.showMessageDialog(null, col);
              }
            }

          }
        });

        TableRowSorter<TableModel> sorter = new TableRowSorter<>(table.getModel());
        table.setRowSorter(sorter);
        List<RowSorter.SortKey> sortKeys = new ArrayList<>();
        int columnIndexToSort = 6; // choose the sorting 
        sortKeys.add(new RowSorter.SortKey(columnIndexToSort, SortOrder.DESCENDING));

         sorter.setSortKeys(sortKeys);
         sorter.setSortable(0,false);
         sorter.setSortable(1,false);
         sorter.setSortable(2,false);
         sorter.setSortable(3,false);
         sorter.setSortable(4,false);
         sorter.setSortable(5,false);
         sorter.setSortable(6,false);
         sorter.setSortable(7,false);
         sorter.setSortable(8,false);
         sorter.setSortable(9,false);
         sorter.setSortable(10,false);
         sorter.sort();

        scrollPane.setViewportView(table);

        btn.setBounds(459,411,130,30);
        getContentPane().add(btn);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    }

        }
}

Please help! As I have been struggling with this problem for some time now!




Aucun commentaire:

Enregistrer un commentaire