Example usage for javax.swing JTable getColumn

List of usage examples for javax.swing JTable getColumn

Introduction

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

Prototype

public TableColumn getColumn(Object identifier) 

Source Link

Document

Returns the TableColumn object for the column in the table whose identifier is equal to identifier, when compared using equals.

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();/* w  ww  .jav  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;//from ww  w  .ja  v a2s  . c  om
    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  w  w.  j av  a  2s.com
        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.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  w  w.j av a2s  .  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)));
    }/* w ww . j  a v a 2s .com*/
}

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));
    }//  w w  w.  j a  v a 2 s . com

    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:com.SE.myPlayer.MusicPlayerGUI.java

public void tableReferesh(JTable songData_Table, String tableName, String columName) {
        int emptyResultSet = 0;

        try {//www.  j  a va2s . c  om
            con = db.getCon();
            stmt = con.createStatement();
            ResultSet rs;

            switch (tableName) {
            case "library":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            case "playlist":
                rs = stmt.executeQuery("select * from library order by " + columName + "");
                break;
            default:
                rs = stmt.executeQuery(
                        "Select library.id_songs, library.song_location, library.song_name, library.song_album, library.song_artist, library.genre, library.year, library.time, library.comment from playlist INNER JOIN library ON library.id_songs = playlist.id_songs AND playlist.playlist_name = '"
                                + tableName + "' order by " + columName + "");
                break;
            }

            DefaultTableModel myModel = new DefaultTableModel() {

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

            String[] songsColumnsName = { "Location", "Name", "Album", "Artist", "Genre", "Year", "Time",
                    "Comment" };
            myModel.setColumnIdentifiers(songsColumnsName);

            ResultSetMetaData rsmd = rs.getMetaData();
            int colNumbers = rsmd.getColumnCount();

            Object[] objects = new Object[colNumbers];

            while (rs.next()) {
                emptyResultSet = 1;
                for (int i = 0; i < colNumbers - 1; i++) {
                    objects[i] = rs.getObject(i + 2);
                }
                myModel.addRow(objects);
            }

            if (emptyResultSet == 0) {
                myModel.addRow(objects);
            }

            songData_Table.setModel(myModel);

            rs = stmt.executeQuery("select col_name from col_name where col_status = 0");

            while (rs.next()) {
                songData_Table.removeColumn(songData_Table.getColumn(rs.getString(1)));
            }

            songData_Table.getTableHeader().removeMouseListener(ma);
            songData_Table.getTableHeader().addMouseListener(ma);
            songData_Table.setDragEnabled(true);
            songData_Table.setDropTarget(new DropTarget() {
                @Override
                public synchronized void drop(DropTargetDropEvent dtde) {

                    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                    Transferable t = dtde.getTransferable();

                    try {
                        if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.javaFileListFlavor);
                            String files = fileList.toString();
                            finalString = convertFileString(files);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        } else if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                            Object fileList = t.getTransferData(DataFlavor.stringFlavor);
                            String fileListString = fileList.toString();

                            fileListString = Arrays.toString(fileListString.split("\\n"));

                            String[] splitLocations = fileListString.split(",\\s");

                            for (int i = 0; i < splitLocations.length; i++) {
                                if (i == 0) {
                                    splitLocations[i] = splitLocations[i].substring(1,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                } else {
                                    splitLocations[i] = splitLocations[i].substring(0,
                                            splitLocations[i].indexOf(".mp3") + 4);
                                }
                            }

                            for (int i = 0; i < splitLocations.length; i++) {
                                splitLocations[i] = sd.getLocations(splitLocations[i]);
                            }
                            finalString = Arrays.asList(splitLocations);
                            if (dropControl == 0 && lastOpen.equals("library")) {
                                songAddDB(finalString);
                            } else if (dropControl == 0 && !lastOpen.equals("library")) {
                                songAddPlaylistFromLibrary(lastOpen, finalString);
                                getSongTable(lastOpen);
                            } else {
                                songAddPlaylistFromLibrary(tableName, finalString);
                            }
                        }
                    } catch (UnsupportedFlavorException | IOException | InvalidDataException
                            | UnsupportedTagException ex) {
                        System.out.println("Error in second drop flavour............" + ex);
                    }
                }
            });

            if (con != null) {
                stmt.close();
                con.close();
            }
        } catch (SQLException e) {
            System.out.println("Error in Stmt " + e);
        }
    }

From source file:edu.ku.brc.specify.extras.ViewToSchemaReview.java

/**
 * /*from w w  w  .j  a v  a  2s.c  o m*/
 */
public void checkSchemaAndViews() {

    Hashtable<String, HashSet<String>> viewFieldHash = new Hashtable<String, HashSet<String>>();

    SpecifyAppContextMgr sacm = (SpecifyAppContextMgr) AppContextMgr.getInstance();

    for (ViewIFace view : sacm.getEntirelyAllViews()) {
        //System.err.println(view.getName() + " ----------------------");
        for (AltViewIFace av : view.getAltViews()) {
            ViewDefIFace vd = av.getViewDef();
            if (vd.getType() == ViewType.form) {
                DBTableInfo ti = DBTableIdMgr.getInstance().getByClassName(vd.getClassName());
                if (ti != null) {
                    HashSet<String> tiHash = viewFieldHash.get(ti.getName());
                    if (tiHash == null) {
                        tiHash = new HashSet<String>();
                        viewFieldHash.put(ti.getName(), tiHash);
                    }

                    FormViewDef fvd = (FormViewDef) vd;
                    for (FormRowIFace row : fvd.getRows()) {
                        for (FormCellIFace cell : row.getCells()) {
                            if (cell.getType() == FormCellIFace.CellType.panel) {
                                FormCellPanelIFace panelCell = (FormCellPanelIFace) cell;
                                for (String fieldName : panelCell.getFieldNames()) {
                                    tiHash.add(fieldName);
                                }

                            } else if (cell.getType() == FormCellIFace.CellType.field
                                    || cell.getType() == FormCellIFace.CellType.subview) {
                                String fieldName = cell.getName();
                                if (!cell.isIgnoreSetGet() && !fieldName.equals("this")) {
                                    DBFieldInfo fi = ti.getFieldByName(fieldName);
                                    if (fi != null) {
                                        //System.err.println("Form Field["+fieldName+"] is in schema.");
                                        tiHash.add(fieldName);
                                    } else {
                                        DBRelationshipInfo ri = ti.getRelationshipByName(fieldName);
                                        if (ri == null) {
                                            //System.err.println("Form Field["+fieldName+"] not in table.");
                                        } else {
                                            tiHash.add(fieldName);
                                        }
                                    }
                                } else if (cell instanceof FormCellFieldIFace) {
                                    FormCellFieldIFace fcf = (FormCellFieldIFace) cell;
                                    if (fcf.getUiType() == FormCellFieldIFace.FieldType.plugin) {
                                        String pluginName = fcf.getProperty("name");
                                        if (StringUtils.isNotEmpty(pluginName)) {
                                            checkPluginForNames(fcf, pluginName, tiHash);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    for (DBTableInfo ti : DBTableIdMgr.getInstance().getTables()) {
        int cnt = 0;

        HashSet<String> tiHash = viewFieldHash.get(ti.getName());
        if (tiHash != null) {
            tblTitle2Name.put(ti.getTitle(), ti.getName());

            //System.err.println(ti.getName() + " ----------------------");
            for (DBFieldInfo fi : ti.getFields()) {
                Boolean isInForm = tiHash.contains(fi.getName());
                modelList.add(
                        createRow(ti.getTitle(), fi.getName(), fi.getTitle(), isInForm, fi.isHidden(), cnt++));
            }

            for (DBRelationshipInfo ri : ti.getRelationships()) {
                Boolean isInForm = tiHash.contains(ri.getName());
                modelList.add(
                        createRow(ti.getTitle(), ri.getName(), ri.getTitle(), isInForm, ri.isHidden(), cnt++));
            }
        }
    }

    viewModel = new ViewModel();
    JTable table = new JTable(viewModel);

    sorter = new TableRowSorter<TableModel>(viewModel);
    searchTF = new JAutoCompTextField(20);

    table.setRowSorter(sorter);

    CellConstraints cc = new CellConstraints();
    PanelBuilder pb = new PanelBuilder(new FormLayout("f:p:g", "p,4px,f:p:g,2px,p:g"));
    SearchBox searchBox = new SearchBox(searchTF, null);

    filterCBX = UIHelper.createComboBox(new String[] { "None", "Not On Form, Not Hidden", "On Form, Hidden" });

    PanelBuilder searchPB = new PanelBuilder(new FormLayout("p,2px,p, f:p:g, p,2px,p", "p"));
    searchPB.add(UIHelper.createI18NFormLabel("SEARCH"), cc.xy(1, 1));
    searchPB.add(searchBox, cc.xy(3, 1));
    searchPB.add(UIHelper.createI18NFormLabel("Filter"), cc.xy(5, 1));
    searchPB.add(filterCBX, cc.xy(7, 1));

    JLabel legend = UIHelper.createLabel(
            "<HTML><li><font color=\"red\">Red</font> - Not on form and not hidden</li><li><font color=\"magenta\">Magenta</font> - On the form , but is hidden</li><li>Black - Correct</li>");
    legend.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
    PanelBuilder legPB = new PanelBuilder(new FormLayout("p,f:p:g", "p"));
    legPB.add(legend, cc.xy(1, 1));

    pb.add(searchPB.getPanel(), cc.xy(1, 1));
    pb.add(UIHelper.createScrollPane(table), cc.xy(1, 3));
    pb.add(legPB.getPanel(), cc.xy(1, 5));
    pb.setDefaultDialogBorder();

    sorter.setRowFilter(null);

    searchTF.getDocument().addDocumentListener(new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            SwingUtilities.invokeLater(new Runnable() {

                /* (non-Javadoc)
                 * @see java.lang.Runnable#run()
                 */
                @Override
                public void run() {
                    if (filterCBX.getSelectedIndex() > 0) {
                        blockCBXUpdate = true;
                        filterCBX.setSelectedIndex(-1);
                        blockCBXUpdate = false;
                    }
                    String text = searchTF.getText();
                    sorter.setRowFilter(text.isEmpty() ? null : RowFilter.regexFilter("^(?i)" + text, 0, 1));
                }
            });
        }
    });

    filterCBX.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (!blockCBXUpdate) {
                        RowFilter<TableModel, Integer> filter = null;
                        int inx = filterCBX.getSelectedIndex();
                        if (inx > 0) {
                            filter = filterCBX.getSelectedIndex() == 1 ? new NotOnFormNotHiddenRowFilter()
                                    : new OnFormIsHiddenRowFilter();
                        }
                        sorter.setRowFilter(filter);
                    }
                }
            });
        }
    });

    table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false));
    table.setDefaultRenderer(Boolean.class, new BiColorBooleanTableCellRenderer());
    table.getColumnModel().getColumn(0).setCellRenderer(new TitleCellFadeRenderer());
    table.getColumnModel().getColumn(3).setCellRenderer(new BiColorTableCellRenderer(true));
    table.getColumnModel().getColumn(2).setCellRenderer(new BiColorTableCellRenderer(false) {
        @SuppressWarnings("unchecked")
        @Override
        public Component getTableCellRendererComponent(JTable tableArg, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel lbl = (JLabel) super.getTableCellRendererComponent(tableArg, value, isSelected, hasFocus,
                    row, column);

            /*if (sorter.getRowFilter() != null)
            {
            System.out.println(" getRowCount:"+sorter.getModel().getRowCount());
            Pair<String, Integer> col1Pair = (Pair<String, Integer>)sorter.getModel().getValueAt(row, 0);
            rowData = modelList.get(col1Pair.second);
                    
            } else
            {
            rowData = modelList.get(row);
            }*/

            //System.out.println(" R2:"+row+"  "+rowData[0]+"/"+rowData[1]+" - "+rowData[3]+"|"+rowData[4]);
            if (value instanceof TableInfo) {
                TableInfo pair = (TableInfo) value;
                Object[] rowData = modelList.get(pair.getSecond());
                lbl.setText(rowData[0].toString());

            } else if (value instanceof Pair<?, ?>) {
                Pair<String, Integer> pair = (Pair<String, Integer>) value;
                Object[] rowData = modelList.get(pair.getSecond());

                boolean isOnForm = rowData[3] instanceof Boolean ? (Boolean) rowData[3]
                        : ((String) rowData[3]).equals("Yes");
                boolean isHidden = rowData[4] instanceof Boolean ? (Boolean) rowData[4]
                        : ((String) rowData[4]).equals("true");

                if (!isOnForm && !isHidden) {
                    lbl.setForeground(Color.RED);

                } else if (isOnForm && isHidden) {
                    lbl.setForeground(Color.MAGENTA);
                } else {
                    lbl.setForeground(Color.BLACK);
                }
                lbl.setText(pair.getFirst());
            } else {
                lbl.setText(value.toString());
            }
            return lbl;
        }

    });

    //UIHelper.makeTableHeadersCentered(table, false);
    UIHelper.calcColumnWidths(table, null);

    //Removing fix all button because fix() method is broken (bug #8087)...

    /*CustomDialog dlg = new CustomDialog((Frame)UIRegistry.getTopWindow(), "", true, CustomDialog.OKCANCELAPPLY, pb.getPanel()) 
    {
    @Override
    protected void applyButtonPressed()
    {
        fix(this);
    }
    };
    dlg.setApplyLabel("Fix All");*/

    CustomDialog dlg = new CustomDialog((Frame) UIRegistry.getTopWindow(), "", true, CustomDialog.OKCANCEL,
            pb.getPanel());

    //... end removing fix all button

    dlg.setVisible(true);

    if (!dlg.isCancelled()) {
        updateSchema();
    }
}

From source file:interfaces.InterfazPrincipal.java

private void BotonBuscarClienteSaldoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BotonBuscarClienteSaldoActionPerformed
    String nombreCliente = nombreClienteBusquedaSaldo.getText();
    //08-11-2014 listar clientes por nombre
    ControladorCliente controladorCliente = new ControladorCliente();
    ArrayList<Cliente> listaClientes = new ArrayList<>();

    if (nombreCliente.equals("")) {
        listaClientes = controladorCliente.obtenerClientes();
    } else {// w w w  . j a va 2 s  . co m
        listaClientes = controladorCliente.obtenerClientes(nombreCliente, 0);
    }

    //08-11-2014 Crear dialogo de bsqueda
    final JDialog dialogoEditar = new JDialog(this);

    dialogoEditar.setTitle("Buscar clientes");
    dialogoEditar.setSize(300, 300);
    dialogoEditar.setResizable(false);

    JPanel panelDialogo = new JPanel();

    panelDialogo.setLayout(new GridBagLayout());

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;

    JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 2;
    c.insets = new Insets(10, 60, 10, 10);
    Font textoGrande = new Font("Arial", 1, 16);
    ediitarTextoPrincipalDialogo.setFont(textoGrande);
    panelDialogo.add(ediitarTextoPrincipalDialogo, c);

    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 2;
    c.insets = new Insets(10, 10, 10, 10);
    final JTable tablaDialogo = new JTable();
    DefaultTableModel modeloTabla = new DefaultTableModel() {

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

    modeloTabla.addColumn("Identificacin");
    modeloTabla.addColumn("Nombre");

    //LLenar tabla
    for (int i = 0; i < listaClientes.size(); i++) {
        Object[] data = { "1", "2" };
        data[0] = listaClientes.get(i).getCliente_id();
        data[1] = listaClientes.get(i).getNombre();
        modeloTabla.addRow(data);
    }

    tablaDialogo.setModel(modeloTabla);
    tablaDialogo.getColumn("Identificacin").setMinWidth(110);
    tablaDialogo.getColumn("Nombre").setMinWidth(110);
    tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    JScrollPane scroll = new JScrollPane(tablaDialogo);
    scroll.setPreferredSize(new Dimension(220, 150));

    panelDialogo.add(scroll, c);

    c.insets = new Insets(0, 0, 0, 10);
    c.gridx = 0;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonGuardarClienteDialogo = new JButton("Elegir");
    panelDialogo.add(botonGuardarClienteDialogo, c);

    c.gridx = 1;
    c.gridy = 2;
    c.gridwidth = 1;
    JButton botonCerrarClienteDialogo = new JButton("Cancelar");
    panelDialogo.add(botonCerrarClienteDialogo, c);

    dialogoEditar.add(panelDialogo);
    dialogoEditar.setVisible(true);

    botonCerrarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialogoEditar.dispose();
        }
    });

    botonGuardarClienteDialogo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = tablaDialogo.getSelectedRow();
            if (row == -1) {
                JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

            } else {
                Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                mostrarIdentificacionCliente.setText(String.valueOf(identificacionCliente));
                String nombreClientePago = String.valueOf(tablaDialogo.getValueAt(row, 1));

                //Limitar a 15 caracteres
                if (nombreClientePago.length() >= 15) {
                    nombreClientePago = nombreClientePago.substring(0, 12);

                }
                textoPersonaSaldo.setText(nombreClientePago);

                DefaultTableModel modeloClientes = (DefaultTableModel) TablaDeSaldoClientes.getModel();
                for (int i = 0; i < modeloClientes.getRowCount(); i++) {
                    modeloClientes.removeRow(i);
                }

                modeloClientes.setRowCount(0);
                ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();

                //SELECT * FROM Flujo_Factura where factura_id in (select factura_id from Factura where cliente_id = 1130614506);
                ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                        " where factura_id in (select factura_id from Factura where cliente_id = "
                                + String.valueOf(identificacionCliente)
                                + " and estado=\"fiado\") order by factura_id");
                double pago = 0.0;

                for (int i = 0; i < flujosCliente.size(); i++) {
                    String[] datos = flujosCliente.get(i);

                    TablaDeSaldoClientes.setModel(modeloClientes);
                    NumberFormat formatter = new DecimalFormat("#0");

                    String valorMovimiento = String.valueOf(formatter.format(Double.parseDouble(datos[4])));
                    Object[] rowData = { datos[1], datos[2], datos[3], valorMovimiento };

                    if (datos[2].equals("deuda")) {
                        pago += Double.parseDouble(datos[4]);
                    } else {
                        pago -= Double.parseDouble(datos[4]);
                    }

                    modeloClientes.addRow(rowData);
                }

                TablaDeSaldoClientes.setModel(modeloClientes);
                NumberFormat formatter = new DecimalFormat("#0");
                textoTotalDebe.setText(String.valueOf(formatter.format(pago)));
                dialogoEditar.dispose();

                //Mostrar en table de clientes los datos
                botonRegistrarAbono.setEnabled(true);
            }

        }
    });
}

From source file:interfaces.InterfazPrincipal.java

private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
    String nombreCliente = nombreClienteReporteCliente.getText();
    String identificacion = identificacionClienteCliente.getText();
    try {//from w  w w.j  a  v a 2 s.c  o  m
        //08-11-2014 listar clientes por nombre
        ControladorCliente controladorCliente = new ControladorCliente();
        ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();

        if (nombreCliente.equals("") && identificacion.equals("")) {
            listaClientes = controladorCliente.obtenerClientes();
        } else {
            int identificacionNumerico = 0;
            if (!identificacion.equals("")) {
                identificacionNumerico = Integer.parseInt(identificacion);
            }
            listaClientes = controladorCliente.obtenerClientes(nombreCliente, identificacionNumerico);
        }

        //08-11-2014 Crear dialogo de bsqueda
        final JDialog dialogoEditar = new JDialog(this);

        dialogoEditar.setTitle("Buscar clientes");
        dialogoEditar.setSize(300, 300);
        dialogoEditar.setResizable(false);

        JPanel panelDialogo = new JPanel();

        panelDialogo.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        c.fill = GridBagConstraints.HORIZONTAL;

        JLabel ediitarTextoPrincipalDialogo = new JLabel("Buscar cliente");
        c.gridx = 0;
        c.gridy = 0;
        c.gridwidth = 2;
        c.insets = new Insets(10, 60, 10, 10);
        Font textoGrande = new Font("Arial", 1, 16);
        ediitarTextoPrincipalDialogo.setFont(textoGrande);
        panelDialogo.add(ediitarTextoPrincipalDialogo, c);

        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 2;
        c.insets = new Insets(10, 10, 10, 10);
        final JTable tablaDialogo = new JTable();
        DefaultTableModel modeloTabla = new DefaultTableModel() {

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

        modeloTabla.addColumn("Identificacin");
        modeloTabla.addColumn("Nombre");

        //LLenar tabla
        for (int i = 0; i < listaClientes.size(); i++) {
            Object[] data = { "1", "2" };
            data[0] = listaClientes.get(i).getCliente_id();
            data[1] = listaClientes.get(i).getNombre();
            modeloTabla.addRow(data);
        }

        tablaDialogo.setModel(modeloTabla);
        tablaDialogo.getColumn("Identificacin").setMinWidth(110);
        tablaDialogo.getColumn("Nombre").setMinWidth(110);
        tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scroll = new JScrollPane(tablaDialogo);
        scroll.setPreferredSize(new Dimension(220, 150));

        panelDialogo.add(scroll, c);

        c.insets = new Insets(0, 0, 0, 10);
        c.gridx = 0;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonGuardarClienteDialogo = new JButton("Elegir");
        panelDialogo.add(botonGuardarClienteDialogo, c);

        c.gridx = 1;
        c.gridy = 2;
        c.gridwidth = 1;
        JButton botonCerrarClienteDialogo = new JButton("Cancelar");
        panelDialogo.add(botonCerrarClienteDialogo, c);

        dialogoEditar.add(panelDialogo);
        dialogoEditar.setVisible(true);

        botonCerrarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                dialogoEditar.dispose();
            }
        });

        botonGuardarClienteDialogo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int row = tablaDialogo.getSelectedRow();
                if (row == -1) {
                    JOptionPane.showMessageDialog(dialogoEditar, "Por favor seleccione una fila");

                } else {
                    Object identificacionCliente = tablaDialogo.getValueAt(row, 0);
                    jTextFieldIdentificacionClienteReporte.setText(String.valueOf(identificacionCliente));
                    botonGenerarReporteCliente.setEnabled(true);
                    dialogoEditar.dispose();

                }

            }
        }); // TODO add your handling code here:     
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "El valor de la identificacin de ser numrico");

    }

}