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:app.RunApp.java

/**
 * Generates TableModel for labels per example values
 * //from  w ww  .j ava2 s  .  c o m
 * @param jtable Table
 * @param labelsPerExample Number of labels per example
 * @return Generated TableModel
 */
private TableModel labelsPerExampleTableModel(JTable jtable, HashMap<Integer, Integer> labelsPerExample) {
    DefaultTableModel tableModel = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //This causes all cells to be not editable
            return false;
        }
    };

    tableModel.addColumn("# Labels");
    tableModel.addColumn("# Examples");
    tableModel.addColumn("Frequency");

    Object[] row = new Object[3];

    double freq;
    int freqCurrent;
    String truncate;

    int max = Utils.maxKey(labelsPerExample);

    for (int i = 0; i <= max; i++) {
        freqCurrent = 0;
        if (labelsPerExample.get(i) != null) {
            freqCurrent = labelsPerExample.get(i);
        }

        freq = freqCurrent * 1.0 / dataset.getNumInstances();

        row[0] = i;
        row[1] = freqCurrent;
        truncate = Double.toString(freq);
        row[2] = MetricUtils.getValueFormatted(truncate, 4);

        tableModel.addRow(row);
    }

    jtable.setModel(tableModel);

    TableColumnModel tcm = jtable.getColumnModel();
    tcm.getColumn(0).setPreferredWidth(80);
    tcm.getColumn(1).setPreferredWidth(50);
    tcm.getColumn(2).setPreferredWidth(70);

    return jtable.getModel();
}

From source file:app.RunApp.java

/**
 * Generates TableModel for imbalanced data
 * /*from www. ja va 2  s . co  m*/
 * @param jtable Table
 * @param dataset Multi-label dataset
 * @return Generated TableModel
 */
private TableModel imbalancedTableModel(JTable jtable, MultiLabelInstances dataset) {
    DefaultTableModel tableModel = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //This causes all cells to be not editable
            return false;
        }
    };

    tableModel.addColumn("Label");
    tableModel.addColumn("IR intra class");
    tableModel.addColumn("IR inter class");
    tableModel.addColumn("STDEV intra class");
    imbalancedLabels = MetricUtils.sortImbalancedDataByIRIntraClass(imbalancedLabels);

    Object[] row = new Object[4];
    double std;
    String truncate;

    ImbalancedFeature current;

    for (int i = 0; i < dataset.getNumLabels(); i++) {
        current = imbalancedLabels[i];

        row[0] = current.getName();

        truncate = Double.toString(current.getIRIntraClass());
        row[1] = MetricUtils.truncateValue(truncate, 5);

        truncate = Double.toString(current.getIRInterClass());
        row[2] = MetricUtils.truncateValue(truncate, 5);

        std = Math.sqrt(current.getVariance());
        row[3] = MetricUtils.truncateValue(std, 4);

        tableModel.addRow(row);
    }

    jtable.setModel(tableModel);

    TableColumnModel tcm = jtable.getColumnModel();
    tcm.getColumn(0).setPreferredWidth(100);
    tcm.getColumn(1).setPreferredWidth(20);
    tcm.getColumn(2).setPreferredWidth(80);
    tcm.getColumn(3).setPreferredWidth(40);

    return jtable.getModel();
}

From source file:com.peterbochs.PeterBochsDebugger.java

public void instructionTableMouseClicked(MouseEvent evt) {
    if (SwingUtilities.isRightMouseButton(evt)) {
        JTable jTable = (JTable) evt.getSource();

        if (jTable == instructionTable) {
            Global.clickedWhichInstructionPanel = 0;
        } else {//from  w  w w.j a v  a2  s  .c o m
            Global.clickedWhichInstructionPanel = 1;
        }

        // select
        Point p = evt.getPoint();
        int rowNumber = jTable.rowAtPoint(p);
        int columnNumber = jTable.columnAtPoint(p);
        ListSelectionModel model = jTable.getSelectionModel();
        model.setSelectionInterval(rowNumber, rowNumber);

        jTable.getColumnModel().getSelectionModel().setSelectionInterval(columnNumber, columnNumber);
        // end select

        getJInstructionPanelPopupMenu().show(evt.getComponent(), evt.getX(), evt.getY());
    }
}

From source file:app.RunApp.java

/**
 * Set frequency of labelsets//  w  w  w. ja  v  a2  s  .  c  o  m
 * 
 * @param jtable Table
 * @param dataset Dataset
 * @param stat Statistics
 * @param cp Plot
 * @return Generated TableModel
 * @throws Exception 
 */
private TableModel labelsetsFrequencyTableModel(JTable jtable, MultiLabelInstances dataset, Statistics stat,
        CategoryPlot cp) throws Exception {
    DefaultTableModel tableModel = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //This causes all cells to be not editable
            return false;
        }
    };

    DefaultCategoryDataset myData = new DefaultCategoryDataset();

    tableModel.addColumn("Labelset Id");
    tableModel.addColumn("# Examples");
    tableModel.addColumn("Frequency");

    double freq;

    //Labelsets frequency
    HashMap<LabelSet, Integer> result = stat.labelCombCount();
    labelsetStringsByFreq = new ArrayList<>(result.size());

    double sum = 0.0;
    Set<LabelSet> keysets = result.keySet();

    Object[] row = new Object[3];

    int count = 1;

    ArrayList<ImbalancedFeature> listImbalanced = new ArrayList();
    ImbalancedFeature temp;

    int value;
    for (LabelSet current : keysets) {
        value = result.get(current);
        temp = new ImbalancedFeature(current.toString(), value);
        listImbalanced.add(temp);
    }

    labelsetsSorted = new ImbalancedFeature[listImbalanced.size()];
    labelsetsFrequency = new double[listImbalanced.size()];

    while (!listImbalanced.isEmpty()) {
        temp = Utils.getMax(listImbalanced);
        labelsetsSorted[count - 1] = temp;
        value = temp.getAppearances();
        labelsetsFrequency[count - 1] = value;
        row[0] = count;
        freq = value * 1.0 / dataset.getNumInstances();
        sum += freq;

        String valueFreq = Double.toString(freq);
        row[1] = value;

        row[2] = MetricUtils.getValueFormatted(valueFreq, 4);
        tableModel.addRow(row);

        String id = "ID: " + Integer.toString(count);

        myData.setValue(freq, id, "");
        labelsetStringsByFreq.add(temp.getName());

        count++;
        listImbalanced.remove(temp);
    }

    jtable.setModel(tableModel);
    jtable.setBounds(jtable.getBounds());

    TableColumnModel tcm = jtable.getColumnModel();
    tcm.getColumn(0).setPreferredWidth(50);
    tcm.getColumn(1).setPreferredWidth(50);
    tcm.getColumn(2).setPreferredWidth(60);

    //graph
    cp.setDataset(myData);

    sum = sum / keysets.size();
    Marker start = new ValueMarker(sum);
    start.setLabelFont(new Font("SansSerif", Font.BOLD, 12));
    start.setLabel("                        Mean: " + MetricUtils.truncateValue(sum, 4));
    start.setPaint(Color.red);
    cp.addRangeMarker(start);

    return jtable.getModel();
}

From source file:app.RunApp.java

/**
 * Set label IR//from  w w  w  .  ja  v a 2 s. c  o  m
 * 
 * @param jtable Table
 * @param stat Statistics
 * @param cp CategoryPlot
 * @return Generated TableModel
 * @throws Exception 
 */
private TableModel irLabelsetsTableModel(JTable jtable, Statistics stat, CategoryPlot cp) throws Exception {
    DefaultTableModel tableModel = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //This causes all cells to be not editable
            return false;
        }
    };

    DefaultCategoryDataset myData = new DefaultCategoryDataset();

    tableModel.addColumn("Labelset id");
    tableModel.addColumn("IR values");

    //Labelsets frequency
    HashMap<LabelSet, Integer> labelsetsFrequency = stat.labelCombCount();
    labelsetStringByIR = new ArrayList<>(labelsetsFrequency.size());

    Set<LabelSet> keysets = labelsetsFrequency.keySet();

    Object[] row = new Object[2];

    int count = 1;
    double IR_labelset;
    int max = getMax(keysets, labelsetsFrequency);

    ArrayList<ImbalancedFeature> listImbalanced = new ArrayList();
    ImbalancedFeature temp;

    int value;

    for (LabelSet current : keysets) {
        value = labelsetsFrequency.get(current);
        IR_labelset = max / (value * 1.0);
        String temp1 = MetricUtils.truncateValue(IR_labelset, 4);
        IR_labelset = Double.parseDouble(temp1);

        temp = new ImbalancedFeature(current.toString(), value, IR_labelset);
        listImbalanced.add(temp);
    }

    labelsetsIRSorted = new ImbalancedFeature[listImbalanced.size()];
    labelsetsByIR = new double[listImbalanced.size()]; //stores IR per labelset

    String truncate;

    while (!listImbalanced.isEmpty()) {
        temp = Utils.getMin(listImbalanced);

        labelsetsIRSorted[count - 1] = temp;
        labelsetsByIR[count - 1] = temp.getIRIntraClass();

        row[0] = count;

        truncate = Double.toString(temp.getIRIntraClass());
        row[1] = MetricUtils.getValueFormatted(truncate, 3);

        tableModel.addRow(row);

        myData.setValue(temp.getIRIntraClass(), Integer.toString(count), "");
        labelsetStringByIR.add(temp.getName());

        count++;
        listImbalanced.remove(temp);
    }

    jtable.setModel(tableModel);
    jtable.setBounds(jtable.getBounds());

    //Resize columns
    TableColumnModel tcm = jtable.getColumnModel();

    tcm.getColumn(0).setPreferredWidth(50);
    tcm.getColumn(1).setPreferredWidth(50);

    //graph
    cp.setDataset(myData);

    //get mean
    double sum = 0;
    for (int i = 0; i < labelsetsIRSorted.length; i++) {
        sum += labelsetsIRSorted[i].getIRIntraClass();
    }
    sum = sum / labelsetsIRSorted.length;

    Marker start = new ValueMarker(sum);
    start.setPaint(Color.blue);
    start.setLabelFont(new Font("SansSerif", Font.BOLD, 12));
    start.setLabel("                        Mean: " + MetricUtils.truncateValue(sum, 4));
    cp.addRangeMarker(start);

    return jtable.getModel();
}

From source file:nl.detoren.ijsco.ui.Mainscreen.java

public JPanel createDeelnemersPanel() {
    JPanel panel = new JPanel(false);
    panel.setBackground(Color.BLACK);
    //panel.setLayout(new GridLayout(1, 0));
    panel.setLayout(new BorderLayout());
    JPanel innerPanel = new JPanel();
    JLabel lbAanwezig = new JLabel("Deelnemers: ");
    innerPanel.add(lbAanwezig, BorderLayout.NORTH);
    tfAanwezig = new JLabel(Integer.toString(status.deelnemers.aantalAanwezig()), 10);
    innerPanel.add(tfAanwezig, BorderLayout.NORTH);
    //innerPanel.setLayout(new GridLayout(1, 0));
    innerPanel.add(new JLabel("Naam:"), BorderLayout.NORTH);
    JTextField deelnemer = new JTextField(15);
    ArrayList<String> words = new ArrayList<>();
    if (status.OSBOSpelers != null) {
        for (Speler s : status.OSBOSpelers.values()) {
            words.add(s.getNaam().trim());
            words.add(Integer.toString(s.getKnsbnummer()));
        }//from w w w .j  a va  2s  . c  o m
    }
    @SuppressWarnings("unused")
    Suggesties suggesties = new Suggesties(deelnemer, this, words, 2);
    innerPanel.add(deelnemer, BorderLayout.NORTH);
    deelnemer.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            actieVoegSpelerToe(deelnemer.getText().trim());
            deelnemer.setText("");
        }
    });

    JButton btVoegToe = new JButton("Voeg toe");
    btVoegToe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            actieVoegSpelerToe(deelnemer.getText().trim());
            deelnemer.setText("");
        }
    });
    innerPanel.add(btVoegToe);
    panel.add(innerPanel);
    // panel_deelnemers.add(new JLabel("Deelnemers IJSCO toernooi"));
    deelnemersModel = new DeelnemersModel(panel, status.deelnemers);
    JTable deelnemersTabel = new JTable(deelnemersModel) {
        private static final long serialVersionUID = -8293073016982337108L;

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            DeelnemersModel model = (DeelnemersModel) getModel();
            // Tooltip
            if (c instanceof JComponent) {
                ((JComponent) c)
                        .setToolTipText(model.getToolTip(convertRowIndexToModel(row), column).toString());
            }

            // Alternate row color
            if (!isRowSelected(row)) {
                c.setBackground(row % 2 == 0 ? Color.WHITE : Color.LIGHT_GRAY);
            }

            // Highlight overruled entries
            if (status.deelnemers.get(convertRowIndexToModel(row)).isOverruleNaam()
                    || status.deelnemers.get(convertRowIndexToModel(row)).isOverruleNaam()) {
                c.setForeground(Color.BLUE);
            } else {
                c.setForeground(Color.BLACK);
            }
            return c;
        }
    };

    deelnemersTabel.getModel().addTableModelListener(new TableModelListener() {

        @Override
        public void tableChanged(TableModelEvent arg0) {
            status.groepen = null;
            status.schemas = null;
            status.schema = null;
            groepenText.setText("");
            schemaModel.setSchemas(null);
            schemaModel.fireTableDataChanged();
            if (status.deelnemers != null && tfAanwezig != null) {
                tfAanwezig.setText(Integer.toString(status.deelnemers.aantalAanwezig()));
            }
            panel.repaint();
        }

    });

    deelnemersTabel.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            logger.log(Level.INFO, "MouseEvent on table fired, type : " + e.toString());
            logger.log(Level.INFO, "Popup trigger? : " + e.isPopupTrigger());
            if (e.isPopupTrigger()) {
                int row = deelnemersTabel.rowAtPoint(e.getPoint());
                JPopupMenu popup = new JPopupMenu();
                JMenuItem menuItem = new JMenuItem("Bewerk speler");
                menuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        logger.log(Level.INFO,
                                "Bewerk Speler  : " + deelnemersTabel.convertRowIndexToModel(row));
                        Speler s = status.deelnemers.get(deelnemersTabel.convertRowIndexToModel(row));
                        BewerkSpelerDialoog rd = new BewerkSpelerDialoog(new JFrame(), "Bewerk Speler", s,
                                deelnemersModel);
                        rd.addWindowListener(new WindowAdapter() {
                            @Override
                            public void windowClosed(WindowEvent e) {
                                System.out.println("closing...");
                            }

                        });
                        rd.setVisible(true);
                    }

                });
                popup.add(menuItem);

                menuItem = new JMenuItem("Verwijder Speler");
                popup.add(menuItem);
                menuItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        logger.log(Level.INFO,
                                "Verwijder Speler  : " + deelnemersTabel.convertRowIndexToModel(row));
                        Speler s = status.deelnemers.get(deelnemersTabel.convertRowIndexToModel(row));
                        status.deelnemers.remove(s);
                        deelnemersModel.fireTableDataChanged();
                    }
                });
                popup.show(e.getComponent(), e.getX(), e.getY());

            }
        }
    });

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(deelnemersTabel);
    innerPanel.add(scrollPane, BorderLayout.CENTER);

    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(deelnemersModel);
    deelnemersTabel.setRowSorter(sorter);

    innerPanel.add(new JLabel("Filter op : "));
    JTextField tfFilter = new JTextField(10);
    tfFilter.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            String text = tfFilter.getText();
            logger.log(Level.INFO, "Filter tabel op : " + text);
            if (text.length() == 0) {
                sorter.setRowFilter(null);
            } else {
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
        }
    });
    innerPanel.add(tfFilter);
    JButton btPasToe = new JButton("Apply");
    btPasToe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            String text = tfFilter.getText();
            logger.log(Level.INFO, "Filter tabel op : " + text);
            if (text.length() == 0) {
                sorter.setRowFilter(null);
            } else {
                sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
        }
    });
    innerPanel.add(btPasToe);
    JButton btWis = new JButton("Wis");
    btWis.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            tfFilter.setText("");
            logger.log(Level.INFO, "Wis filter");
            sorter.setRowFilter(null);
        }
    });
    innerPanel.add(btWis);

    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(0), 30);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(1), 55);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(2), 170);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(3), 40);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(4), 40);
    Utils.fixedColumSize(deelnemersTabel.getColumnModel().getColumn(5), 30);
    Utils.fixedComponentSize(scrollPane, 400, 580);
    return panel;
}

From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java

private void setJobQueueTableDefaults(JTable jobQueueTable, JobQueueTableModel jobQueueTableModel) {
    jobQueueTableModel.addTableModelListener(new JobQueueTableModelListener());
    jobQueueTable.setModel(jobQueueTableModel);
    jobQueueTable.setSurrendersFocusOnKeystroke(true);
    jobQueueTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    jobQueueTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    jobQueueTable.setColumnSelectionAllowed(true);
    jobQueueTable.setRowSelectionAllowed(true);
    TableRenderer renderer = new TableRenderer();
    TableColumn col = jobQueueTable.getColumnModel().getColumn(0);
    int width = 200;
    col.setPreferredWidth(width);/*from  w w w .  j  a va2  s.  c  om*/
    col.setWidth(width);
    col.setCellRenderer(renderer);

    col = jobQueueTable.getColumnModel().getColumn(1);
    width = 1400;
    col.setPreferredWidth(width);
    col.setWidth(width);
    col.setCellRenderer(renderer);
}

From source file:op.tools.SYSTools.java

public static void packColumn(JTable table, int vColIndex, int margin) {
    TableModel model = table.getModel();
    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
    TableColumn col = colModel.getColumn(vColIndex);
    int width = 0;

    // Get width of column header
    TableCellRenderer renderer = col.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }/*ww  w  . j  a  v  a2 s.  c om*/
    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;
    // Set the width
    col.setPreferredWidth(width);

    OPDE.debug("packColumn/3: col=" + vColIndex + "  width=" + width);
}

From source file:org.apache.cayenne.modeler.editor.ObjEntityRelationshipPanel.java

protected void rebuildTable(ObjEntity entity) {
    final ObjRelationshipTableModel model = new ObjRelationshipTableModel(entity, mediator, this);

    model.addTableModelListener(new TableModelListener() {

        public void tableChanged(TableModelEvent e) {
            if (table.getSelectedRow() >= 0) {
                ObjRelationship rel = model.getRelationship(table.getSelectedRow());
                enabledResolve = rel.getSourceEntity().getDbEntity() != null;
                resolveMenu.setEnabled(enabledResolve);
            }/*from  www . j  av  a2 s  .  c om*/
        }
    });

    table.setModel(model);
    table.setRowHeight(25);
    table.setRowMargin(3);

    TableColumn col = table.getColumnModel().getColumn(ObjRelationshipTableModel.REL_TARGET_PATH);
    col.setCellEditor(new DbRelationshipPathComboBoxEditor());
    col.setCellRenderer(new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
            setToolTipText(
                    "To choose relationship press enter two times.To choose next relationship press dot.");
            return this;
        }
    });

    col = table.getColumnModel().getColumn(ObjRelationshipTableModel.REL_DELETE_RULE);
    JComboBox deleteRulesCombo = Application.getWidgetFactory().createComboBox(DELETE_RULES, false);
    deleteRulesCombo.setFocusable(false);
    deleteRulesCombo.setEditable(true);
    ((JComponent) deleteRulesCombo.getEditor().getEditorComponent()).setBorder(null);
    deleteRulesCombo.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
    deleteRulesCombo.setSelectedIndex(0); // Default to the first value
    col.setCellEditor(Application.getWidgetFactory().createCellEditor(deleteRulesCombo));

    tablePreferences.bind(table, null, null, null, ObjRelationshipTableModel.REL_NAME, true);
}

From source file:org.apache.jmeter.protocol.http.visualizers.RequestViewHTTP.java

private void setFirstColumnPreferredAndMaxWidth(JTable table) {
    TableColumn column = table.getColumnModel().getColumn(0);
    column.setMaxWidth(300);//from   w ww  .jav a2  s  . c  o m
    column.setPreferredWidth(160);
}