Example usage for javax.swing JTable getModel

List of usage examples for javax.swing JTable getModel

Introduction

In this page you can find the example usage for javax.swing JTable getModel.

Prototype

public TableModel getModel() 

Source Link

Document

Returns the TableModel that provides the data displayed by this JTable .

Usage

From source file:mt.listeners.InteractiveRANSAC.java

public void updateRANSAC() {

    negcount = 0;/*from  w  w w  .  j  a  va  2s  .  com*/
    negtimediff = 0;
    averageshrink = 0;
    catindex = 0;
    negsegments = new ArrayList<Pair<LinearFunction, ArrayList<PointFunctionMatch>>>();
    ArrayList<Rateobject> allrates = new ArrayList<Rateobject>();
    ArrayList<Averagerate> averagerates = new ArrayList<Averagerate>();

    ++updateCount;

    dataset.removeAllSeries();
    this.dataset.addSeries(Tracking.drawPoints(mts, calibrations));

    @SuppressWarnings("unchecked")
    ArrayList<Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>>> segments = Tracking
            .findAllFunctions(points, function, maxError, minInliers, maxDist);

    if (segments == null || segments.size() == 0) {
        --updateCount;
        return;
    }

    // sort the segments according to time HORIZONTAL to each other and the
    // PointFunctionMatches internally
    sort(segments);

    final LinearFunction linear = new LinearFunction();
    int linearcount = 1;
    i = 1;
    segment = 1;
    int count = 0;

    int rescount = 0;
    int catcount = 0;
    double timediff = 0;
    double restimediff = 0;

    double averagegrowth = 0;

    double growthrate = 0;
    double shrinkrate = 0;

    double minstartY = leastStart(segments);

    double minstartX = Double.MAX_VALUE;
    double minendX = Double.MAX_VALUE;
    double catfrequ = 0;
    double resfrequ = 0;
    double lifetime = 0;

    ArrayList<Double> previousendX = new ArrayList<Double>();
    ResultsTable rt = new ResultsTable();
    ResultsTable rtAll = new ResultsTable();

    List<Pair<Float, Float>> starttimerates = new ArrayList<Pair<Float, Float>>();
    List<Pair<Float, Float>> catstarttimerates = new ArrayList<Pair<Float, Float>>();
    for (final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> result : segments) {
        if (LinearFunction.slopeFits(result.getB(), linear, minSlope, maxSlope)) {

            final Pair<Double, Double> minMax = Tracking.fromTo(result.getB());

            double startX = minMax.getA();
            double endX = minMax.getB();

            if (startX < minstartX) {

                minstartX = startX;
            }
            if (endX < minendX) {

                minendX = endX;
            }

            Polynomial<?, Point> polynomial = (Polynomial) result.getA();

            dataset.addSeries(
                    Tracking.drawFunction(polynomial, minMax.getA(), minMax.getB(), 0.5, "Segment " + segment));

            if (functionChoice > 0) {
                Tracking.setColor(chart, i, new Color(255, 0, 0));
                Tracking.setDisplayType(chart, i, true, false);
                Tracking.setStroke(chart, i, 0.5f);
                chart.setTitle("Length plot for" + " " + this.inputfiles[row].getName());
            } else {
                Tracking.setColor(chart, i, new Color(0, 128, 0));
                Tracking.setDisplayType(chart, i, true, false);
                Tracking.setStroke(chart, i, 2f);
                chart.setTitle("Length plot for" + " " + this.inputfiles[row].getName());
            }

            ++i;

            if (functionChoice > 0) {

                dataset.addSeries(Tracking.drawFunction(linear, minMax.getA(), minMax.getB(), 0.5,
                        "Linear Segment " + segment));

                Tracking.setColor(chart, i, new Color(0, 128, 0));
                Tracking.setDisplayType(chart, i, true, false);
                Tracking.setStroke(chart, i, 2f);

                ++i;

            }

            double startY = polynomial.predict(startX);
            double linearrate = linear.getCoefficient(1);
            if (linearrate > 0 && startY - minstartY > restolerance && previousendX.size() > 0) {
                rescount++;
                restimediff += -previousendX.get(previousendX.size() - 1) + startX;

            }

            if (linearrate > 0) {

                count++;
                growthrate = linearrate;
                // Ignore last growth event for getting fcat
                if (points.get(points.size() - 1).getW()[0] - endX >= tptolerance)
                    catcount++;
                timediff += endX - startX;
                lifetime = endX - startX;
                averagegrowth += linearrate;
                lifecount.add(new ValuePair<Integer, Double>(count, lifetime));

                Rateobject velocity = new Rateobject(linearrate * calibrations[0] / calibrations[2],
                        (int) (startX * calibrations[2]), (int) (endX * calibrations[2]));
                allrates.add(velocity);
                rt.incrementCounter();
                rt.addValue("Start time", startX * calibrations[2]);
                rt.addValue("End time", endX * calibrations[2]);
                rt.addValue("Growth velocity", linearrate * calibrations[0] / calibrations[2]);

                Pair<Float, Float> startrate = new ValuePair<Float, Float>((float) startX, (float) linearrate);

                starttimerates.add(startrate);
            }
            if (linearrate < 0) {

                negcount++;
                negtimediff += endX - startX;

                shrinkrate = linearrate;
                averageshrink += linearrate;

                rt.incrementCounter();
                rt.addValue("Start time", startX * calibrations[2]);
                rt.addValue("End time", endX * calibrations[2]);
                rt.addValue("Growth velocity", linearrate * calibrations[0] / calibrations[2]);

                Pair<Float, Float> startrate = new ValuePair<Float, Float>((float) startX, (float) linearrate);

                starttimerates.add(startrate);

            }
            if (linearrate > 0) {
                previousendX.add(endX);

            }
            dataset.addSeries(Tracking.drawPoints(Tracking.toPairList(result.getB()), calibrations,
                    "Inliers " + segment));

            Tracking.setColor(chart, i, new Color(255, 0, 0));
            Tracking.setDisplayType(chart, i, false, true);
            Tracking.setSmallUpTriangleShape(chart, i);

            ++i;
            ++segment;

        } else {
            System.out.println("Removed segment because slope is wrong.");

        }

    }

    if (this.detectCatastrophe) {

        if (segments.size() < 2) {

            System.out.println("Only two points found");

        } else {
            for (int catastrophy = 0; catastrophy < segments.size() - 1; ++catastrophy) {
                final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> start = segments.get(catastrophy);
                final Pair<AbstractFunction2D, ArrayList<PointFunctionMatch>> end = segments
                        .get(catastrophy + 1);

                double tStart = start.getB().get(start.getB().size() - 1).getP1().getL()[0];
                double tEnd = end.getB().get(0).getP1().getL()[0];

                final double lStart = start.getB().get(start.getB().size() - 1).getP1().getL()[1];
                final double lEnd = end.getB().get(0).getP1().getL()[1];

                final ArrayList<Point> catastropyPoints = new ArrayList<Point>();

                for (final Point p : points)
                    if (p.getL()[0] >= tStart && p.getL()[0] <= tEnd)
                        catastropyPoints.add(p);

                if (catastropyPoints.size() > 2) {
                    if (Math.abs(lStart - lEnd) >= this.minDistanceCatastrophe) {
                        // maximally 1.1 timepoints between points on a line
                        final Pair<LinearFunction, ArrayList<PointFunctionMatch>> fit = Tracking
                                .findFunction(catastropyPoints, new LinearFunction(), 0.75, 3, 1.1);

                        if (fit != null) {
                            if (fit.getA().getM() < 0) {
                                sort(fit);
                                negsegments.add(fit);
                                double minY = Math.min(fit.getB().get(0).getP1().getL()[1],
                                        fit.getB().get(fit.getB().size() - 1).getP1().getL()[1]);
                                double maxY = Math.max(fit.getB().get(0).getP1().getL()[1],
                                        fit.getB().get(fit.getB().size() - 1).getP1().getL()[1]);

                                final Pair<Double, Double> minMax = Tracking.fromTo(fit.getB());

                                double startX = minMax.getA();
                                double endX = minMax.getB();

                                double linearrate = fit.getA().getCoefficient(1);

                                if (linearrate < 0) {
                                    dataset.addSeries(Tracking.drawFunction((Polynomial) fit.getA(),
                                            minMax.getA() - 1, minMax.getB() + 1, 0.1, minY - 2.5, maxY + 2.5,
                                            "CRansac " + catastrophy));
                                    negcount++;
                                    negtimediff += endX - startX;

                                    shrinkrate = linearrate;
                                    averageshrink += linearrate;

                                    rt.incrementCounter();
                                    rt.addValue("Start time", startX * calibrations[2]);
                                    rt.addValue("End time", endX * calibrations[2]);
                                    rt.addValue("Growth velocity",
                                            linearrate * calibrations[0] / calibrations[2]);

                                    Pair<Float, Float> startrate = new ValuePair<Float, Float>((float) startX,
                                            (float) linearrate);

                                    starttimerates.add(startrate);

                                    Rateobject velocity = new Rateobject(
                                            linearrate * calibrations[0] / calibrations[2],
                                            (int) (startX * calibrations[2]), (int) (endX * calibrations[2]));
                                    allrates.add(velocity);
                                    Tracking.setColor(chart, i, new Color(0, 0, 255));
                                    Tracking.setDisplayType(chart, i, true, false);
                                    Tracking.setStroke(chart, i, 2f);

                                    ++i;
                                    dataset.addSeries(Tracking.drawPoints(Tracking.toPairList(fit.getB()),
                                            calibrations, "C(inl) " + catastrophy));

                                    Tracking.setColor(chart, i, new Color(0, 0, 255));
                                    Tracking.setDisplayType(chart, i, false, true);
                                    Tracking.setShape(chart, i, ShapeUtils.createDownTriangle(4f));

                                    ++i;
                                }
                            }
                        }

                    }

                    else {
                        System.out.println("Catastrophy height not sufficient " + Math.abs(lStart - lEnd)
                                + " < " + this.minDistanceCatastrophe);

                    }
                }

            }

        }
    }

    if (this.detectmanualCatastrophe) {

        catindex++;
        catstarttimerates = ManualCat(segments, allrates, shrinkrate, rt);

    }

    if (count > 0)
        averagegrowth /= count;

    if (catcount > 0)

        catfrequ = catcount / (timediff * calibrations[2]);

    if (rescount > 0)

        resfrequ = rescount / (restimediff * calibrations[2]);

    if (negcount > 0)
        averageshrink /= negcount;

    if (resfrequ < 0)
        resfrequ = 0;

    rt.show("Rates(real units) for" + " " + this.inputfile.getName());
    averageshrink *= calibrations[0] / calibrations[2];
    averagegrowth *= calibrations[0] / calibrations[2];
    rtAll.incrementCounter();
    rtAll.addValue("Average Growth", averagegrowth);
    rtAll.addValue("Growth events", count);
    rtAll.addValue("Average Shrink", averageshrink);
    rtAll.addValue("Shrink events", negcount);
    rtAll.addValue("Catastrophe Frequency", catfrequ);
    rtAll.addValue("Catastrophe events", catcount);
    rtAll.addValue("Rescue Frequency", resfrequ);
    rtAll.addValue("Rescue events", rescount);
    // rtAll.show("Average Rates and Frequencies (real units)");

    starttimerates.addAll(catstarttimerates);
    sortTime(starttimerates);

    for (int index = 0; index < starttimerates.size() - 1; ++index) {

        int prevsign = (int) Math.signum(starttimerates.get(index).getB());
        int nextsign = (int) Math.signum(starttimerates.get(index + 1).getB());

        if (nextsign == prevsign)
            wrongfile = true;
        else
            wrongfile = false;

        wrongfileindex = new ValuePair<Boolean, Integer>(wrongfile, row);
        wrongfileindexlist.put(row, wrongfile);
    }
    table.getModel().setValueAt(new DecimalFormat("#.###").format(averagegrowth), row, 1);
    table.getModel().setValueAt(new DecimalFormat("#.###").format(averageshrink), row, 2);
    table.getModel().setValueAt(new DecimalFormat("#").format(count), row, 3);
    table.getModel().setValueAt(new DecimalFormat("#").format(negcount), row, 4);
    table.getModel().setValueAt(new DecimalFormat("#.###").format(catfrequ), row, 5);
    table.getModel().setValueAt(new DecimalFormat("#.###").format(resfrequ), row, 6);
    if (wrongfileindexlist.get(row) != null) {
        table.getModel().setValueAt(wrongfileindexlist.get(row).toString(), row, 7);
    }
    int size = 100;
    table.getColumnModel().getColumn(0).setPreferredWidth(size);
    table.getColumnModel().getColumn(1).setPreferredWidth(size);
    table.getColumnModel().getColumn(2).setPreferredWidth(size);
    table.getColumnModel().getColumn(3).setPreferredWidth(size);
    table.getColumnModel().getColumn(4).setPreferredWidth(size);
    table.getColumnModel().getColumn(5).setPreferredWidth(size);
    table.getColumnModel().getColumn(6).setPreferredWidth(size);
    table.getColumnModel().getColumn(7).setPreferredWidth(size);
    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int rowA, int col) {

            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, rowA, col);

            String status = (String) table.getModel().getValueAt(row, 7);
            if ("true".equals(status)) {
                setBackground(Color.GRAY);

            } else {
                setBackground(Color.GRAY);
            }
            return this;
        }
    });
    table.validate();

    scrollPane.validate();

    Averagerate avrate = new Averagerate(averagegrowth, averageshrink, catfrequ, resfrequ, count, negcount,
            catcount, rescount, this.inputfile);
    averagerates.add(avrate);
    Compilepositiverates.put(row, allrates);

    Compileaverage.put(row, avrate);

    --updateCount;

}

From source file:semaforo.Semaforo.java

public synchronized void updateTableWeek(JTable TableWeek, int index, int tamano) {

    Settings settings = Controller.getSettings();

    //  TableWeek.getColumnModel().getColumn(0).setPreferredWidth(120);
    //  TableWeek.getColumnModel().getColumn(9).setPreferredWidth(120);
    // CustomRenderer cr = new CustomRenderer(TableWeek.getDefaultRenderer(Object.class), Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY);
    //  TableWeek.setDefaultRenderer(Object.class, cr);
    DefaultTableModel model = (DefaultTableModel) TableWeek.getModel();

    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(3);/*  w w w .  jav  a  2s .  c  o  m*/

    int num = Math.min(settings.getTickers().size(), model.getRowCount());
    if (TableWeek.getModel().getRowCount() > 0) {
        num = Math.min(settings.getTickers().size(), TableWeek.getModel().getRowCount());
    }

    for (int i = 0; i < num; i++) {
        for (int m = 0; m < TableTicker.getModel().getRowCount(); m++) {
            if (TableTicker != null && TableTicker.getModel() != null) {
                if (TableTicker.getModel().getValueAt(m, 0) != null) {
                    if (TableTicker.getModel().getValueAt(m, 0)
                            .equals(settings.getTickers().get(i).getName())) {
                        model.setValueAt(String.format("%.2f", settings.getTickers().get(i).getMinValue(index)),
                                m, 0);
                        model.setValueAt(String.format("%.2f", settings.getTickers().get(i).getMaxValue(index)),
                                m, tamano); //TODO: Parametrizar
                        //                            JOptionPane.showMessageDialog(null,index+"", "", JOptionPane.ERROR_MESSAGE);
                        if (index == 13) {
                            DDBB.updateTicker(TableTicker.getModel().getValueAt(m, 0).toString(),
                                    String.format("%.2f", settings.getTickers().get(i).getMinValue(index)),
                                    String.format("%.2f", settings.getTickers().get(i).getMaxValue(index)));
                        }
                    }
                }
            }
        }
    }
}

From source file:semaforo.Semaforo.java

public synchronized void loadTableWeek(JTable TableWeek, int index) {
    Settings settings = Controller.getSettings();

    //TableWeek.getColumnModel().getColumn(0).setPreferredWidth(350); //150
    TableWeek.setRowHeight(20); //40
    //TableWeek.getColumnModel().getColumn(9).setPreferredWidth(350);//150
    TableWeek.setFont(new Font("Arial", Font.BOLD, 12));//18

    CustomRenderer cr = new CustomRenderer(TableWeek.getDefaultRenderer(Object.class), Color.LIGHT_GRAY,
            Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY);
    TableWeek.setDefaultRenderer(Object.class, cr);
    DefaultTableModel model = (DefaultTableModel) TableWeek.getModel();
    Object[] o = new Object[10];

    JTableHeader header = TableWeek.getTableHeader();
    header.setPreferredSize(new Dimension(10, 30)); //100
    TableWeek.getTableHeader().setFont(new Font("Arial", Font.BOLD, 15));

    /* DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
     centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
     TableWeek.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
     TableWeek.getColumnModel().getColumn(9).setCellRenderer(centerRenderer);
     TableWeek.setDefaultRenderer(String.class, centerRenderer);*/
    int num = settings.getTickers().size();

    /*   while(DDBB.loadData) {
     try {//from   w w  w  .  java  2s.  co  m
     Thread.sleep(500);
     } catch (InterruptedException ex) {
     Logger.getLogger(Semaforo.class.getName()).log(Level.SEVERE, null, ex);
     }
     }*/
    if (TableWeek.getModel().getRowCount() > 0) {
        num = Math.min(settings.getTickers().size(), TableWeek.getModel().getRowCount());
    }

    for (int i = 0; i < num; i++) {
        o[0] = settings.getTickers().get(i).getMinValue(index);
        o[9] = settings.getTickers().get(i).getMaxValue(index);
        model.addRow(o);
    }
}

From source file:semaforo.Semaforo.java

public void loadTableCells(JTable TableWeek, int index, Map<String, List<Integer>> ht, int tamano) {
    System.out.println("---------------------------->" + TableWeek.getName());
    Settings settings = Controller.getSettings();

    for (int i = 0; i < tamano - 1; i++) {
        TableWeek.getColumnModel().getColumn(i)
                .setCellRenderer(new ResetCellRenderer(TableWeek.getDefaultRenderer(Object.class),
                        Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, i));
    }/*from   w  w  w . j a va  2 s  .  c  om*/

    int[] my_positions = new int[num_positions];
    boolean[] paint = new boolean[num_positions];

    for (int j = 0; j < num_positions; j++) {
        my_positions[j] = -1;
        paint[j] = false;
    }

    //int num = settings.getTickers().size();
    // if (TableWeek.getModel().getRowCount() > 0) {
    int num = Math.min(settings.getTickers().size(), TableWeek.getModel().getRowCount());
    //   }

    // synchronized (Controller.positionLock) {
    for (int row = 0; row < num; row++) {

        if (ht.get(TableTicker.getValueAt(row, 0)) != null) {
            //                if(row>24)JOptionPane.showMessageDialog(null, row+"");
            List<Integer> listInt = ht
                    .get(TableTicker.getValueAt(row, 0) /*settings.getTickers().get(row).getName()*/);
            my_positions[row] = -1;
            if (!listInt.isEmpty() && settings.getTickers().get(row).isHistory()) {
                //                    int col = ht.get(TableTicker.getValueAt(row, 0)).get(index) + 1;
                int col = ht.get(TableTicker.getValueAt(row, 0)).get(index);
                my_positions[row] = col;
            }

        }
    }

    // }
    //Modify the cell
    // if (num > 0) {
    for (int col = 0; col < tamano/*settings.getTickers().size()*/; col++) {

        //     if (paint[col]) {
        TableWeek.getColumnModel().getColumn(col).setCellRenderer(
                new MyCellRenderer(TableWeek.getDefaultRenderer(Object.class), index, Color.LIGHT_GRAY,
                        Color.LIGHT_GRAY, Color.LIGHT_GRAY, Color.LIGHT_GRAY, my_positions, col));
        //     }

    }
    //  }
}

From source file:de.tor.tribes.ui.windows.TribeTribeAttackFrame.java

/**
 * Show result frame for calculated attacks
 */// ww w.j  av a 2 s . co m
private void showResults(List<Attack> pAttacks) {
    mLogFrame.setVisible(false);
    jResultsTable.invalidate();
    DefaultTableModel resultModel = new javax.swing.table.DefaultTableModel(new Object[][] {},
            new String[] { "Herkunft", "Einheit", "Ziel", "Start", "Ankunft", "Typ", "" }) {

        Class[] types = new Class[] { Village.class, UnitHolder.class, Village.class, Date.class, Date.class,
                Integer.class, Boolean.class };

        @Override
        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }

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

    //renderer, which marks send times red if attack is impossible to send
    DefaultTableRenderer renderer = new DefaultTableRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component c = new DateCellRenderer().getTableCellRendererComponent(table, value, isSelected,
                    hasFocus, row, column);
            JLabel l = (JLabel) c;
            Boolean impossible = (Boolean) table.getModel().getValueAt(row, 6);
            if (impossible.booleanValue()) {
                l.setText("<html><nobr><font color='#FF0000'>" + l.getText() + "</font></nobr></html>");
            }
            return c;
        }
    };

    jResultsTable.setDefaultRenderer(Date.class, renderer);
    jResultsTable.setDefaultRenderer(Integer.class,
            new NoteIconCellRenderer(NoteIconCellRenderer.ICON_TYPE.NOTE));
    jResultsTable.setDefaultEditor(Integer.class, new NoteIconCellEditor(NoteIconCellEditor.ICON_TYPE.NOTE));
    jResultsTable.setDefaultRenderer(UnitHolder.class, new UnitCellRenderer());
    jResultsTable.setDefaultEditor(UnitHolder.class, new UnitCellEditor());
    jResultsTable.setDefaultRenderer(Village.class, new VillageCellRenderer());
    jResultsTable.setRowHeight(24);
    List<Long> startTimes = new LinkedList<Long>();
    int impossibleAttacks = 0;

    for (Attack a : pAttacks) {
        long targetTime = a.getArriveTime().getTime();
        long startTime = targetTime - (long) (DSCalculator.calculateMoveTimeInSeconds(a.getSource(),
                a.getTarget(), a.getUnit().getSpeed()) * 1000);
        boolean impossible = false;
        if (!startTimes.contains(startTime)) {
            startTimes.add(startTime);
        } else {
            impossibleAttacks++;
            impossible = true;
        }
        resultModel.addRow(new Object[] { a.getSource(), a.getUnit(), a.getTarget(), new Date(startTime),
                a.getArriveTime(), a.getType(), impossible });
    }

    jResultsTable.setModel(resultModel);

    TableColumnExt columns = jResultsTable.getColumnExt(5);
    columns.setVisible(false);
    jResultsTable.getTableHeader().setDefaultRenderer(new DefaultTableHeaderRenderer());

    jResultFrame.setVisible(true);

    if (impossibleAttacks > 0) {
        String message = "";
        if (impossibleAttacks == 1) {
            message = "<html>Ein berechneter Angriff hat einen bereits verwendeten Abschickzeitpunkt.<br/>Der entsprechende Angriff ist in der Tabelle rot markiert</html>";
        } else {
            message = "<html>" + impossibleAttacks
                    + " berechnete Angriffe haben identische Abschickzeitpunkte.<br/>Die entsprechenden Angriffe sind in der Tabelle rot markiert</html>";
        }
        showInfo(message, true);
    }
}

From source file:de.tor.tribes.ui.windows.TribeTribeAttackFrame.java

/**
 * Create detail frames shown after calculation
 *///from w  ww  .j  a v  a  2  s . c o  m
private void buildDetailedStatistics(HashMap<Village, String> attackMappings,
        List<Village> pNotAssignedVillages) {
    // <editor-fold defaultstate="collapsed" desc="Build not assigned source table">
    Collections.sort(pNotAssignedVillages);
    DefaultTableModel sourcesModel = new javax.swing.table.DefaultTableModel(new Object[][] {},
            new String[] { "Spieler", "Dorf" }) {

        private Class[] cTypes = new Class[] { Tribe.class, Village.class };

        @Override
        public Class getColumnClass(int columnIndex) {
            return cTypes[columnIndex];
        }
    };
    for (Village notAssigned : pNotAssignedVillages) {
        Tribe t = notAssigned.getTribe();
        if (t == null) {
            sourcesModel.addRow(new Object[] { Barbarians.getSingleton(), notAssigned });
        } else {
            sourcesModel.addRow(new Object[] { t, notAssigned });
        }
    }
    jNotAssignedSourcesTable.setModel(sourcesModel);
    TableRowSorter<TableModel> sourcesSorter = new TableRowSorter<TableModel>(sourcesModel);
    jNotAssignedSourcesTable.setRowSorter(sourcesSorter);
    DefaultTableCellRenderer headerRenderer = new SortableTableHeaderRenderer();
    for (int i = 0; i < jNotAssignedSourcesTable.getColumnCount(); i++) {
        jNotAssignedSourcesTable.getColumn(jNotAssignedSourcesTable.getColumnName(i))
                .setHeaderRenderer(headerRenderer);
    }
    jNotAssignedSourcesTable.revalidate();
    //</editor-fold>
    // <editor-fold defaultstate="collapsed" desc="Build attacks per target table">
    DefaultTableModel tableModel = new javax.swing.table.DefaultTableModel(new Object[][] {},
            new String[] { "Spieler", "Dorf", "Angriffe" }) {

        Class[] types = new Class[] { Tribe.class, Village.class, String.class };

        @Override
        public Class getColumnClass(int columnIndex) {
            return types[columnIndex];
        }
    };
    List<Village> notFullTargets = new LinkedList<Village>();
    Iterator<Village> keys = attackMappings.keySet().iterator();
    while (keys.hasNext()) {
        Village key = keys.next();
        Tribe t = key.getTribe();
        //int notAssignedAmount = attackMappings.get(key);
        String attackCount = attackMappings.get(key);
        String[] split = attackCount.split("/");
        int notAssignedAmount = Integer.parseInt(split[1]) - Integer.parseInt(split[0]);
        if (t != Barbarians.getSingleton()) {
            tableModel.addRow(new Object[] { t, key, attackCount });
        } else {
            tableModel.addRow(new Object[] { "Barbaren", key, attackCount });
        }
        if (notAssignedAmount > 0) {
            notFullTargets.add(key);
        }
    }
    jTargetDetailsTable.setModel(tableModel);
    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tableModel);
    jTargetDetailsTable.setRowSorter(sorter);
    DefaultTableCellRenderer coloredRenderer = new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component c = new DefaultTableCellRenderer().getTableCellRendererComponent(table, value, isSelected,
                    hasFocus, row, row);
            String t = ((DefaultTableCellRenderer) c).getText();
            ((DefaultTableCellRenderer) c).setText(t);
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            int r = table.convertRowIndexToModel(row);
            String sVal = (String) model.getValueAt(r, 2);
            String[] split = sVal.split("/");
            long max = Long.parseLong(split[1]);
            long v = Long.parseLong(split[0]);
            long diff = max - v;
            Color back = Color.RED;
            if (v == 0) {
                //color stays red
            } else if (v == max) {
                back = Color.GREEN;
            } else {
                float posv = 100.0f * (float) diff / (float) max;
                posv = ((int) posv / 10) * 10;
                posv /= 100;
                Color LAST_SEGMENT = new Color(255, 100, 0);
                int red = (int) Math.rint(
                        (float) LAST_SEGMENT.getRed() * (1.0f - posv) + (float) Color.YELLOW.getRed() * posv);
                int green = (int) Math.rint((float) LAST_SEGMENT.getGreen() * (1.0f - posv)
                        + (float) Color.YELLOW.getGreen() * posv);
                int blue = (int) Math.rint(
                        (float) LAST_SEGMENT.getBlue() * (1.0f - posv) + (float) Color.YELLOW.getBlue() * posv);
                if (red < 0) {
                    red = 0;
                }
                if (green < 0) {
                    green = 0;
                }
                if (blue < 0) {
                    blue = 0;
                }
                if (red > 254) {
                    red = 254;
                }
                if (green > 254) {
                    green = 254;
                }
                if (blue > 254) {
                    blue = 254;
                }
                back = new Color(red, green, blue);
            }
            DefaultTableCellRenderer renderer = ((DefaultTableCellRenderer) c);
            if (!isSelected) {
                renderer.setBackground(back);
            }
            return c;
        }
    };
    jTargetDetailsTable.setDefaultRenderer(Village.class, coloredRenderer);
    jTargetDetailsTable.setDefaultRenderer(Integer.class, coloredRenderer);
    jTargetDetailsTable.setDefaultRenderer(String.class, coloredRenderer);
    jTargetDetailsTable.setDefaultRenderer(Tribe.class, coloredRenderer);
    for (int i = 0; i < jTargetDetailsTable.getColumnCount(); i++) {
        jTargetDetailsTable.getColumn(jTargetDetailsTable.getColumnName(i)).setHeaderRenderer(headerRenderer);
    }
    jTargetDetailsTable.revalidate();
    //</editor-fold>
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *//* www  . j  a  v a2  s  .c  o  m*/
private void initColumnSizes(final JTable tableArg, final JButton theSaveBtn) throws Exception {
    TableModel tblModel = tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    Element uploadDefs = null;
    if (WorkbenchTask.isCustomizedSchema()) {
        uploadDefs = XMLHelper.readFileToDOM4J(
                new File(UIRegistry.getAppDataDir() + File.separator + "specify_workbench_upload_def.xml"));
    } else {
        uploadDefs = XMLHelper.readDOMFromConfigDir("specify_workbench_upload_def.xml");
    }

    //UIRegistry.getInstance().hookUpUndoableEditListener(cellEditor);

    Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>();
    wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(wbtmis);

    DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema();

    columnMaxWidths = new Integer[tableArg.getColumnCount()];
    for (int i = 0; i < wbtmis.size() /*tableArg.getColumnCount()*/; i++) {
        TableCellRenderer headerRenderer = tableArg.getColumnModel().getColumn(i).getHeaderRenderer();
        WorkbenchTemplateMappingItem wbtmi = wbtmis.elementAt(i);

        // Now go retrieve the data length
        int fieldWidth = WorkbenchDataItem.getMaxWBCellLength();
        DBTableInfo ti = databaseSchema.getInfoById(wbtmi.getSrcTableId());
        if (ti != null) {
            DBFieldInfo fi = ti.getFieldByName(wbtmi.getFieldName());
            if (fi != null) {
                wbtmi.setFieldInfo(fi);
                //System.out.println(fi.getName()+"  "+fi.getLength()+"  "+fi.getType());
                if (RecordTypeCodeBuilder.getTypeCode(fi) == null && fi.getLength() > 0) {
                    fieldWidth = Math.min(fi.getLength(), WorkbenchDataItem.getMaxWBCellLength());
                }
            } else {
                log.error("Can't find field with name [" + wbtmi.getFieldName() + "]");
            }
        } else {
            log.error("Can't find table [" + wbtmi.getSrcTableId() + "]");
        }
        columnMaxWidths[i] = new Integer(fieldWidth);
        GridCellEditor cellEditor = getCellEditor(wbtmi, fieldWidth, theSaveBtn, uploadDefs);
        column = tableArg.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        //comp.setBackground(Color.WHITE);

        int maxWidth = headerWidth + 10;
        TableModel m = tableArg.getModel();
        FontMetrics fm = comp.getFontMetrics(comp.getFont());
        for (int row = 0; row < tableArg.getModel().getRowCount(); row++) {
            String text = m.getValueAt(row, i).toString();
            maxWidth = Math.max(maxWidth, fm.stringWidth(text) + 10);
            //log.debug(i+" "+maxWidth);
        }

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        //log.debug(Math.max(maxWidth, cellWidth));
        //log.debug(Math.min(Math.max(maxWidth, cellWidth), 400));
        column.setPreferredWidth(Math.min(Math.max(maxWidth, cellWidth), 400));

        column.setCellEditor(cellEditor);
    }
    //tableArg.setCellEditor(cellEditor);
}

From source file:app.RunApp.java

/**
 * Action for Clear button from principal tab
 * /*from   w  w w  .ja v  a2s  .  c  o  m*/
 * @param evt Event
 * @param jtable Table
 */
private void buttonClearActionPerformedPrincipal(java.awt.event.ActionEvent evt, JTable jtable) {
    TableModel tmodel = jtable.getModel();

    for (int i = 0; i < tmodel.getRowCount(); i++) {
        tmodel.setValueAt(Boolean.FALSE, i, 2);
    }

    clearTableMetricsPrincipal();
}

From source file:app.RunApp.java

/**
 * Action for None button from principal tab
 * //  w  ww  .j a va2 s  .c o m
 * @param evt Event
 * @param jtable Table
 */
private void buttonNoneActionPerformedPrincipal(java.awt.event.ActionEvent evt, JTable jtable) {
    TableModel tmodel = jtable.getModel();

    for (int i = 0; i < tmodel.getRowCount(); i++) {
        tmodel.setValueAt(Boolean.FALSE, i, 2);
    }

    jtable.setModel(tmodel);
    jtable.repaint();
}

From source file:app.RunApp.java

/**
 * Action for None button from multiple datasets tab
 * //w  w  w  .  j  av a  2 s. c  o  m
 * @param evt Event
 * @param jtable Table
 */
private void buttonNoneActionPerformedMulti(java.awt.event.ActionEvent evt, JTable jtable) {
    TableModel tmodel = jtable.getModel();

    for (int i = 0; i < tmodel.getRowCount(); i++) {
        tmodel.setValueAt(Boolean.FALSE, i, 1);
    }

    jtable.setModel(tmodel);
    jtable.repaint();
}