Java, change a cell content as a function of anoth

2020-01-25 02:07发布

I need some help for my problem. I have a table with e.g. a double column and a string column. If the value in the double column is negativ, the string should be "negativ". And the other way if the value is positiv, the string should be "positiv". The problem is now if I edit the double value in the jTable, the string should also be updated.

Update to my question, the actual code look like this: But it doesn't work, because the string in the second column wont be updated after I edit the first column value. It only works when I start the program the first time.

import java.util.Vector;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;

public class ExampleRemoveAddRows extends JFrame {

    private Object[] columnNames = {"Double", "positiv / negativ"};
    private Object[][] data = {
        {new Double(10.0), "positiv"},
        {new Double(-10.0), "negativ"},
        {new Double(20.0), "positiv"},
        {new Double(-30.0), "negativ"}
    };
    private JTable table;
    private DefaultTableModel model;

    public ExampleRemoveAddRows() {
        model = new DefaultTableModel(data, columnNames) {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
            @Override
            public Object getValueAt(int row, int column) {  
                if (column == 1) {
                    double number = Double.parseDouble(this.getValueAt(row, 0).toString());
                    System.out.println(number);
                    System.out.println("good");
                    System.out.println((number < 0) ? "negativ" : "positiv");
                    return "C: "+ this.getValueAt(row, 0);//((number < 0) ? "negativ" : "positiv");
                } else {
                    return super.getValueAt(row, column);
                }
            }  
        };
        table = new JTable(model);        
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ExampleRemoveAddRows frame = new ExampleRemoveAddRows();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

Thanks for your help.

Sam

2条回答
戒情不戒烟
2楼-- · 2020-01-25 03:00

You do indeed have access to the TableModel, if I'm not mistaken, through TableModelEvent.getSource().

Just to provide a basic example (mostly because the one sentance answer hardly seems like much of an answer):

TableModel model = (TableModel)te.getSource();
Double number = model.getValueAt(te.firstRow, 0);
model.setValueAt(((number < 0) ? "negativ":"positiv"), te.firstRow, 1);
查看更多
相关推荐>>
3楼-- · 2020-01-25 03:14

I've revised your sscce to show the alternate approach suggested here. Note the alternate ways to get a Double constant. I've also re-factored the String constrants.

Addendum: In helpful comments, @kleopatra observes that querying the model directly will always produce the correct result, but a TableModelListener will only see changes to column 0, not column 1. The simple expedient is to make column 1 non-editable, as its value depends completely on column 0.

@Override
public boolean isCellEditable(int row, int col) {
    return col == 0;
}

The first example below uses DefaultTableModel:

import javax.swing.*;
import javax.swing.table.*;

/** @see https://stackoverflow.com/a/13628183/230513 */
public class ExampleRemoveAddRows extends JFrame {

    public static final String NEGATIVE = "negativ";
    public static final String POSITIVE = "positiv";
    private Object[] columnNames = {"Double", POSITIVE + " / " + NEGATIVE};
    private Object[][] data = {
        {10d, null},
        {-10.0, null},
        {Double.valueOf(30), null},
        {Double.valueOf("-30"), null}
    };
    private JTable table;
    private DefaultTableModel model;

    public ExampleRemoveAddRows() {
        model = new DefaultTableModel(data, columnNames) {

            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }

            @Override
            public boolean isCellEditable(int row, int col) {
                return col == 0;
            }

            @Override
            public Object getValueAt(int row, int col) {
                if (col == 1) {
                    double number = (Double) this.getValueAt(row, 0);
                    return (number < 0) ? NEGATIVE : POSITIVE;
                } else {
                    return super.getValueAt(row, col);
                }
            }

            @Override
            public void setValueAt(Object aValue, int row, int col) {
                super.setValueAt(aValue, row, col);
                fireTableCellUpdated(row, 1); // may have changed
            }
        };
        table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ExampleRemoveAddRows frame = new ExampleRemoveAddRows();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

This variation extends AbstractTableModel:

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.table.*;

/**
* @see https://stackoverflow.com/a/13628183/230513
*/
public class ExampleRemoveAddRows extends JFrame {

    public static final String NEGATIVE = "negativ";
    public static final String POSITIVE = "positiv";

    public ExampleRemoveAddRows() {
        DoubleModel model = new DoubleModel();
        model.add(10.1);
        model.add(-10.2);
        model.add(Double.valueOf(30.1));
        model.add(Double.valueOf("-30.2"));
        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ExampleRemoveAddRows frame = new ExampleRemoveAddRows();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    private class DoubleModel extends AbstractTableModel {

        List<Double> data = new ArrayList<Double>();

        public void add(Double d) {
            data.add(d);
        }

        @Override
        public int getRowCount() {
            return data.size();
        }

        @Override
        public int getColumnCount() {
            return 2;
        }

        @Override
        public String getColumnName(int col) {
            if (col == 0) {
                return "Double";
            } else {
                return POSITIVE + " / " + NEGATIVE;
            }
        }

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == 0) {
                return Double.class;
            } else {
                return String.class;
            }
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return col == 0;
        }

        @Override
        public Object getValueAt(int row, int col) {
            if (col == 0) {
                return data.get(row);
            } else {
                double number = (Double) this.getValueAt(row, 0);
                return (number < 0) ? NEGATIVE : POSITIVE;
            }
        }

        @Override
        public void setValueAt(Object aValue, int row, int col) {
            if (col == 0) {
                data.set(row, (Double) aValue);
                fireTableRowsUpdated(row, row);
            }
        }
    }
}
查看更多
登录 后发表回答