简体   繁体   中英

jTable entering data into a column

I have a jTable which I m using to enter student exam marks. When I enter marks into the "Marks" column it automatically check the Grade according to the entered marks and put it into the next column (which is "grade") ,same row. It works fine. When you have more than one row to enter marks there is a problem. We'll assume there are three student to enter marks, if you enter marks into the last row (student comes last in the table) the Grade will not updated. you have to come by order top to bottom to update Grade . Help me on this . Thanks. Here is my code :

 for (int i = 0; i < jTable1.getRowCount(); i++) {
if(!(jTable1.getValueAt(i, 2).toString().equals(""))){
if(!(Integer.parseInt(jTable1.getValueAt(i, 2).toString())>100)){
        String mark = jTable1.getValueAt(i, 2).toString();
        int mk = Integer.parseInt(mark);
        if (mk >= 75) {
            jTable1.setValueAt("A", i, 3);
        } else if (mk < 75 && mk >= 65) {
            jTable1.setValueAt("B", i, 3);
        } else if (mk < 65 && mk >= 55) {
            jTable1.setValueAt("C", i, 3);
        } else if (mk < 55 && mk >= 35) {
            jTable1.setValueAt("S", i, 3);
        } else{
        jTable1.setValueAt("F", i, 3);
        }}}

I'd use a CellRenderer to achieve this. Something like this. You can extends DefaultTableCellRenderer implementation

public class MarkCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component c = super.getTableCellRendererComponent(jTable, value, isSelected, hasFocus, row, column);
        if (c instanceof JLabel) {
            JLabel label = (JLabel) c;
            label.setHorizontalAlignment(JLabel.RIGHT);
            Integer mk = Integer.parseInt(value.toString());//this is not very clean
            String text= null;
            if (mk >= 75) {
               text="A";
            } else if (mk < 75 && mk >= 65) {
               text="B";
            } else if (mk < 65 && mk >= 55) {
               text="C";
            } else if (mk < 55 && mk >= 35) {
               text="S";
            } else{
                text="F";
            }
            label.setText(text);
    }
        return c;
    }
}

And you set like

myTable.getColumnModel().getColumn(2).setCellRenderer(new MarkCellRenderer());

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