Example usage for javax.swing JTable getColumnModel

List of usage examples for javax.swing JTable getColumnModel

Introduction

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

Prototype

public TableColumnModel getColumnModel() 

Source Link

Document

Returns the TableColumnModel that contains all column information of this table.

Usage

From source file:marytts.tools.redstart.AdminWindow.java

private void buildPromptTable() {

    this.promptArray = this.currentSession.getPromptArray();

    System.out.println("Loading prompts...");
    Test.output("Array contains " + promptArray.length + " prompts.");

    // Make column names array
    String[] columnNames = new String[3];
    columnNames[REC_STATUS_COLUMN] = "Status";
    columnNames[BASENAME_COLUMN] = "Basename";
    columnNames[PROMPT_TEXT_COLUMN] = "Prompt Preview";

    // Now create the table itself        
    JTable table = new JTable(new PromptTableModel(promptArray, columnNames, redAlertMode));
    table.setColumnSelectionAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Set alignment for the status colum to centered
    DefaultTableCellRenderer renderer = new ClippingColorRenderer();
    renderer.setHorizontalAlignment(JTextField.CENTER);
    table.getColumnModel().getColumn(REC_STATUS_COLUMN).setCellRenderer(renderer);

    // Set selection highlight colour to light blue
    table.setSelectionBackground(new java.awt.Color(153, 204, 255));

    // Add listeners
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent evt) {
            displayPromptText();//from  w  ww .  j  a v  a  2  s.  c  o  m
        }
    });

    // Store the table in an instance field accessible to the entire class
    this.jTable_PromptSet = table;

    Thread recordingStatusInitialiser = new Thread() {
        public void run() {
            updateAllRecStatus();
        }
    };
    recordingStatusInitialiser.start();

    // Display table in the appropriate component pane
    jScrollPane_PromptSet.setViewportView(table);

    if (promptArray.length > 0) {
        table.setRowSelectionInterval(0, 0); // Show first row of prompt table as selected               
        displayPromptText(); // Display the prompt text for the first prompt in the prompt display pane 
    }
    setColumnWidths();

    System.out.println("Total " + table.getRowCount() + " prompts loaded.");

}

From source file:mt.listeners.InteractiveRANSAC.java

public void updateRANSAC() {

    negcount = 0;//www  . j  a v  a2 s . c  o m
    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:com.haskins.cloudtrailviewer.sidebar.AbstractChart.java

private void addTable() {

    defaultTableModel.addColumn("");
    defaultTableModel.addColumn("Property");
    defaultTableModel.addColumn("Value");

    final LegendColourRenderer cellRenderer = new LegendColourRenderer();
    final JTable table = new JTable(defaultTableModel) {

        private static final long serialVersionUID = -6272711583089149891L;

        @Override//  w  ww. ja  v a 2 s.  c o m
        public TableCellRenderer getCellRenderer(int row, int column) {
            if (column == 0) {
                return cellRenderer;
            }
            return super.getCellRenderer(row, column);
        }

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

    table.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent me) {

            JTable table = (JTable) me.getSource();
            String value = (String) defaultTableModel.getValueAt(table.getSelectedRow(), 1);

            if (me.getClickCount() == 2) {

                if (value.startsWith("i-")) {

                    Event event = null;
                    AllFilter filter = new AllFilter();
                    filter.setNeedle(value);
                    for (Event searchEvent : eventDb.getEvents()) {

                        if (filter.passesFilter(searchEvent)) {

                            event = searchEvent;
                            break;
                        }
                    }

                    if (event != null) {
                        AwsAccount account = AccountDao.getAccountByAcctNum(event.getRecipientAccountId());
                        ResourceDetailRequest request = new ResourceDetailRequest(account, event.getAwsRegion(),
                                "EC2 Instance", value);
                        ResourceDetailDialog.showDialog(CloudTrailViewer.frame, request);
                    }
                }

            } else if (me.getClickCount() == 1) {

                try {
                    eventTablePanel.setFilterString(value);
                } catch (Exception ex) {
                    LOGGER.log(Level.WARNING, "Problem responding to mouse event on chart table", ex);
                }
            }
        }
    });

    TableColumn column;
    for (int i = 0; i < 3; i++) {
        column = table.getColumnModel().getColumn(i);

        switch (i) {
        case 0:
            column.setMinWidth(15);
            column.setMaxWidth(15);
            column.setPreferredWidth(15);
            break;

        case 2:
            column.setMinWidth(70);
            column.setMaxWidth(70);
            column.setPreferredWidth(70);
            break;
        }
    }

    JScrollPane tablecrollPane = new JScrollPane(table);
    tablecrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    this.add(tablecrollPane, BorderLayout.CENTER);
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * @param table//from   w w w. j  a  va  2 s.c  o  m
 * @param model
 * @return
 */
public static JTable autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                    r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        preferredWidthTotal += col.getPreferredWidth();
        colWidths[i] = width;

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            colModel.getColumn(i).setPreferredWidth(colWidths[i]);
        }
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);

    return table;
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Calculates and sets the each column to it preferred size.  NOTE: This
 * method also sets the table height to 10 rows.
 * /*www.j a  v  a  2  s .  c  om*/
 * @param table the table to fix up
 * @param numRowsHeight the number of rows to make the table height (or null not to set it)
 */
public static void calcColumnWidths(final JTable table, final Integer numRowsHeight, final Integer maxWidth) {
    if (table != null) {
        JTableHeader header = table.getTableHeader();

        TableCellRenderer defaultHeaderRenderer = null;

        if (header != null) {
            defaultHeaderRenderer = header.getDefaultRenderer();
        }

        TableColumnModel columns = table.getColumnModel();
        TableModel data = table.getModel();

        int margin = columns.getColumnMargin(); // only JDK1.3

        int rowCount = data.getRowCount();

        int totalWidth = 0;

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);

            int columnIndex = column.getModelIndex();

            int width = -1;

            TableCellRenderer h = column.getHeaderRenderer();

            if (h == null)
                h = defaultHeaderRenderer;

            if (h != null) // Not explicitly impossible
            {
                Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1,
                        i);

                width = c.getPreferredSize().width;
            }

            for (int row = rowCount - 1; row >= 0; --row) {
                TableCellRenderer r = table.getCellRenderer(row, i);

                Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                        false, row, i);

                width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer

                if (maxWidth != null) {
                    width = Math.min(width, maxWidth);
                }
            }

            if (width >= 0) {
                column.setPreferredWidth(width + margin); // <1.3: without margin
            } else {
                // ???
            }

            totalWidth += column.getPreferredWidth();
        }

        // If you like; This does not make sense for two many columns!
        Dimension size = table.getPreferredScrollableViewportSize();
        //if (totalWidth > size.width)
        {
            if (numRowsHeight != null) {
                size.height = Math.min(size.height, table.getRowHeight() * numRowsHeight);
            }
            size.width = totalWidth;
            table.setPreferredScrollableViewportSize(size);
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.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
 *///from w ww .  j  a va2  s.  c  o m
private void initColumnSizes(final JTable tableArg) {
    ColTableModel tblModel = (ColTableModel) tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    TableCellRenderer headerRenderer = tableArg.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < tblModel.getColumnCount(); i++) {
        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;

        /*
        if (DEBUG) {
        System.out.println("Initializing width of column "
                           + i + ". "
                           + "headerWidth = " + headerWidth
                           + "; cellWidth = " + cellWidth);
        }*/

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:semaforo.Semaforo.java

public void formateaCabeceroWeeks(JTable table) {

    table.getColumnModel().getColumn(0).setHeaderRenderer(new ColumnHeaderRenderer());
    table.getColumnModel().getColumn(table.getColumnCount() - 1).setHeaderRenderer(new ColumnHeaderRenderer());

    for (int i = 1; i < table.getColumnCount() - 1; i++) {

        table.getColumnModel().getColumn(i)
                .setHeaderRenderer(new ColumnHeaderRenderer(new Color(240, 240, 120)));
    }// ww w  .j a v  a 2s . c om
}

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  v  a2s .  c  o m*/

    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:library.Form_Library.java

License:asdf

public static void resizeColumnWidth(JTable table) {
    final TableColumnModel columnModel = table.getColumnModel();
    for (int column = 0; column < table.getColumnCount(); column++) {
        int width = 15; // Min width
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, column);
            Component comp = table.prepareRenderer(renderer, row, column);
            width = Math.max(comp.getPreferredSize().width + 1, width);
        }// w w  w.ja va  2s  .  c o m
        if (width > 300) {
            width = 300;
        }
        columnModel.getColumn(column).setPreferredWidth(width);
    }
}

From source file:com.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

public JPanel createDetailsView() {
    final VFSJFileChooser chooser = getFileChooser();

    JPanel p = new JPanel(new BorderLayout());

    final JTable detailsTable = new JTable(getDetailsTableModel()) {
        // Handle Escape key events here
        @Override// w ww  . jav  a2  s .  co  m
        protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
            if ((e.getKeyCode() == KeyEvent.VK_ESCAPE) && (getCellEditor() == null)) {
                // We are not editing, forward to filechooser.
                chooser.dispatchEvent(e);

                return true;
            }

            return super.processKeyBinding(ks, e, condition, pressed);
        }

        @Override
        public void tableChanged(TableModelEvent e) {
            super.tableChanged(e);

            if (e.getFirstRow() == TableModelEvent.HEADER_ROW) {
                // update header with possibly changed column set
                updateDetailsColumnModel(this);
            }
        }
    };

    //        detailsTable.setRowSorter(getRowSorter());
    detailsTable.setAutoCreateColumnsFromModel(false);
    detailsTable.setComponentOrientation(chooser.getComponentOrientation());
    //detailsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    detailsTable.setShowGrid(false);
    detailsTable.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);

    //        detailsTable.addKeyListener(detailsKeyListener);
    Font font = list.getFont();
    detailsTable.setFont(font);
    detailsTable.setIntercellSpacing(new Dimension(0, 0));

    TableCellRenderer headerRenderer = new AlignableTableHeaderRenderer(
            detailsTable.getTableHeader().getDefaultRenderer());
    detailsTable.getTableHeader().setDefaultRenderer(headerRenderer);

    TableCellRenderer cellRenderer = new DetailsTableCellRenderer(chooser);
    detailsTable.setDefaultRenderer(Object.class, cellRenderer);

    // So that drag can be started on a mouse press
    detailsTable.getColumnModel().getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    detailsTable.addMouseListener(getMouseHandler());
    // No need to addListSelectionListener because selections are forwarded
    // to our JList.

    // 4835633 : tell BasicTableUI that this is a file list
    detailsTable.putClientProperty("Table.isFileList", Boolean.TRUE);

    if (listViewWindowsStyle) {
        detailsTable.addFocusListener(repaintListener);
    }

    JTableHeader header = detailsTable.getTableHeader();
    header.setUpdateTableInRealTime(true);
    header.addMouseListener(detailsTableModel.new ColumnListener());
    header.setReorderingAllowed(true);

    // TAB/SHIFT-TAB should transfer focus and ENTER should select an item.
    // We don't want them to navigate within the table
    ActionMap am = SwingUtilities.getUIActionMap(detailsTable);
    am.remove("selectNextRowCell");
    am.remove("selectPreviousRowCell");
    am.remove("selectNextColumnCell");
    am.remove("selectPreviousColumnCell");
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
    detailsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);

    JScrollPane scrollpane = new JScrollPane(detailsTable);
    scrollpane.setComponentOrientation(chooser.getComponentOrientation());
    LookAndFeel.installColors(scrollpane.getViewport(), "Table.background", "Table.foreground");

    // Adjust width of first column so the table fills the viewport when
    // first displayed (temporary listener).
    scrollpane.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            JScrollPane sp = (JScrollPane) e.getComponent();
            fixNameColumnWidth(sp.getViewport().getSize().width);
            sp.removeComponentListener(this);
        }
    });

    // 4835633.
    // If the mouse is pressed in the area below the Details view table, the
    // event is not dispatched to the Table MouseListener but to the
    // scrollpane.  Listen for that here so we can clear the selection.
    scrollpane.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
            JScrollPane jsp = ((JScrollPane) e.getComponent());
            JTable table = (JTable) jsp.getViewport().getView();

            if (!e.isShiftDown()
                    || (table.getSelectionModel().getSelectionMode() == ListSelectionModel.SINGLE_SELECTION)) {
                clearSelection();

                TableCellEditor tce = table.getCellEditor();

                if (tce != null) {
                    tce.stopCellEditing();
                }
            }
        }
    });

    detailsTable.setForeground(list.getForeground());
    detailsTable.setBackground(list.getBackground());

    if (listViewBorder != null) {
        scrollpane.setBorder(listViewBorder);
    }

    p.add(scrollpane, BorderLayout.CENTER);

    detailsTableModel.fireTableStructureChanged();

    return p;
}