Example usage for javax.swing JTable getModel

List of usage examples for javax.swing JTable getModel

Introduction

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

Prototype

public TableModel getModel() 

Source Link

Document

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

Usage

From source file:app.RunApp.java

/**
 * Set frequency of labelsets/*from  ww  w.j a v  a 2  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  www . j av  a2s. 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()));
        }/*www. j ava  2 s  . co  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:nl.xs4all.home.freekdb.b52reader.gui.MainGuiTest.java

private void testFetchedArticles(boolean zeroBackgroundBrowserMaxCount)
        throws InterruptedException, InvocationTargetException {
    String fetchedValue = "fetched";

    if (zeroBackgroundBrowserMaxCount) {
        Mockito.when(mockConfiguration.getBackgroundBrowserMaxCount()).thenReturn(0);
    }//from  ww w .j  av  a2s  .c  o  m

    MainGui mainGui = new MainGui(mockManyBrowsersPanel);
    mainGui.setMainCallbacks(mockMainCallbacks);

    Mockito.when(mockConfiguration.useSpanTable()).thenReturn(true);
    Mockito.when(mockConfiguration.getFetchedValue()).thenReturn(fetchedValue);

    mainGui.initializeBackgroundBrowsersPanel(mockFrame, mockConfiguration);
    mainGui.initializeGui(TestUtilities.getSixTestArticles());

    waitForGuiTasks();

    JTable table = (JTable) findComponent(mockContentPane, JTable.class);
    assertNotNull(table);

    assertEquals(fetchedValue, table.getModel().getValueAt(2, 0));
}

From source file:nz.govt.natlib.ndha.manualdeposit.metadata.MetaDataElementCellEditor.java

public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected,
        final int rowIndex, final int vColIndex) {
    // 'value' is value contained in the cell located at (rowIndex,
    // vColIndex)

    final MetaDataTableModel model = (MetaDataTableModel) table.getModel();
    final IMetaDataTypeExtended type = model.getRow(rowIndex);
    final int maximumLength = type.getMaximumLength();
    switch (type.getDataType()) {
    case Date:
        cal.setFormats(DATE_FORMAT);/*  w ww .ja  v a 2s.  c o  m*/
        component = componentDatePicker;
        ((JXDatePicker) component).setDate(parseDate((String) value));
        break;
    case MultiSelect:
        component = componentCombo;
        final JComboBox box = (JComboBox) component;
        box.removeAllItems();
        box.addItem(new MetaDataListValues("", "", 0));
        int itemNo = 1;
        for (MetaDataListValues listValue : type.getListItems()) {
            box.addItem(listValue);
            if (listValue.getValue().equals(value)) {
                box.setSelectedIndex(itemNo);
            }
            itemNo++;
        }
        ((JComboBox) component).setSelectedItem((String) value);
        break;
    case Boolean:
        component = componentCheck;
        final boolean boolValue = Boolean.parseBoolean((String) value);
        ((JCheckBox) component).setSelected(boolValue);
        break;
    case Integer:
        component = componentWholeNumber;
        ((WholeNumberField) component).setText((String) value);
        break;
    case RealNumber:
        component = componentDecimal;
        ((DecimalNumberField) component).setText((String) value);
        break;
    case Text:
    default:
        component = componentText;
        ((MaxLengthTextField) component).setMaximumLength(maximumLength);
        if (value == null) {
            ((MaxLengthTextField) component).setText("");
        } else {
            ((MaxLengthTextField) component).setText((String) value);
        }
    }
    if (theStandardFont != null) {
        component.setFont(theStandardFont);
    }
    return component;
}

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();
    }//from ww w .ja  va2 s  .  c  o  m
    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.util.DbAttributePathComboBoxEditor.java

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
        int column) {
    this.model = (ObjAttributeTableModel) table.getModel();
    this.row = row;
    treeModel = createTreeModelForComboBox(row);
    if (treeModel == null) {
        return new JLabel("You should select table for this ObjectEntity");
    }/*w  w w.j a  v  a  2 s.c  o m*/
    initializeCombo(model, row, table);

    String dbAttributePath = ((JTextComponent) (comboBoxPathChooser).getEditor().getEditorComponent())
            .getText();
    previousEmbeddedLevel = StringUtils.countMatches(dbAttributePath, ".");
    return comboBoxPathChooser;
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java

private JTable createTable(final ViewState state) {
    JTable table;
    final ModelGraph selected = state.getSelected();
    if (selected != null) {
        final Vector<Vector<String>> rows = new Vector<Vector<String>>();
        ConcurrentHashMap<String, String> keyToGroupMap = new ConcurrentHashMap<String, String>();
        Metadata staticMet = selected.getModel().getStaticMetadata();
        Metadata inheritedMet = selected.getInheritedStaticMetadata(state);
        Metadata completeMet = new Metadata();
        if (staticMet != null) {
            completeMet.replaceMetadata(staticMet.getSubMetadata(state.getCurrentMetGroup()));
        }//from  w w  w .jav a 2  s.  c  o  m
        if (selected.getModel().getExtendsConfig() != null) {
            for (String configGroup : selected.getModel().getExtendsConfig()) {
                Metadata extendsMetadata = state.getGlobalConfigGroups().get(configGroup).getMetadata()
                        .getSubMetadata(state.getCurrentMetGroup());
                for (String key : extendsMetadata.getAllKeys()) {
                    if (!completeMet.containsKey(key)) {
                        keyToGroupMap.put(key, configGroup);
                        completeMet.replaceMetadata(key, extendsMetadata.getAllMetadata(key));
                    }
                }
            }
        }
        if (inheritedMet != null) {
            Metadata inheritedMetadata = inheritedMet.getSubMetadata(state.getCurrentMetGroup());
            for (String key : inheritedMetadata.getAllKeys()) {
                if (!completeMet.containsKey(key)) {
                    keyToGroupMap.put(key, "__inherited__");
                    completeMet.replaceMetadata(key, inheritedMetadata.getAllMetadata(key));
                }
            }
        }
        List<String> keys = completeMet.getAllKeys();
        Collections.sort(keys);
        for (String key : keys) {
            if (key.endsWith("/envReplace")) {
                continue;
            }
            String values = StringUtils.join(completeMet.getAllMetadata(key), ",");
            Vector<String> row = new Vector<String>();
            row.add(keyToGroupMap.get(key));
            row.add(key);
            row.add(values);
            row.add(Boolean.toString(Boolean.parseBoolean(completeMet.getMetadata(key + "/envReplace"))));
            rows.add(row);
        }
        table = new JTable();// rows, new Vector<String>(Arrays.asList(new
                             // String[] { "key", "values", "envReplace" })));
        table.setModel(new AbstractTableModel() {
            public String getColumnName(int col) {
                switch (col) {
                case 0:
                    return "group";
                case 1:
                    return "key";
                case 2:
                    return "values";
                case 3:
                    return "envReplace";
                default:
                    return null;
                }
            }

            public int getRowCount() {
                return rows.size() + 1;
            }

            public int getColumnCount() {
                return 4;
            }

            public Object getValueAt(int row, int col) {
                if (row >= rows.size()) {
                    return null;
                }
                String value = rows.get(row).get(col);
                if (value == null && col == 3) {
                    return "false";
                }
                if (value == null && col == 0) {
                    return "__local__";
                }
                return value;
            }

            public boolean isCellEditable(int row, int col) {
                if (row >= rows.size()) {
                    return selected.getModel().getStaticMetadata().containsGroup(state.getCurrentMetGroup());
                }
                if (col == 0) {
                    return false;
                }
                String key = rows.get(row).get(1);
                return key == null || (selected.getModel().getStaticMetadata() != null
                        && selected.getModel().getStaticMetadata().containsKey(getKey(key, state)));
            }

            public void setValueAt(Object value, int row, int col) {
                if (row >= rows.size()) {
                    Vector<String> newRow = new Vector<String>(
                            Arrays.asList(new String[] { null, null, null, null }));
                    newRow.add(col, (String) value);
                    rows.add(newRow);
                } else {
                    Vector<String> rowValues = rows.get(row);
                    rowValues.add(col, (String) value);
                    rowValues.remove(col + 1);
                }
                this.fireTableCellUpdated(row, col);
            }

        });
        MyTableListener tableListener = new MyTableListener(state);
        table.getModel().addTableModelListener(tableListener);
        table.getSelectionModel().addListSelectionListener(tableListener);
    } else {
        table = new JTable(new Vector<Vector<String>>(),
                new Vector<String>(Arrays.asList(new String[] { "key", "values", "envReplace" })));
    }

    // table.setFillsViewportHeight(true);
    table.setSelectionBackground(Color.cyan);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableCellRenderer cellRenderer = new TableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel field = new JLabel((String) value);
            if (column == 0) {
                field.setForeground(Color.gray);
            } else {
                if (isSelected) {
                    field.setBorder(new EtchedBorder(1));
                }
                if (table.isCellEditable(row, 1)) {
                    field.setForeground(Color.black);
                } else {
                    field.setForeground(Color.gray);
                }
            }
            return field;
        }

    };
    TableColumn groupCol = table.getColumnModel().getColumn(0);
    groupCol.setPreferredWidth(75);
    groupCol.setCellRenderer(cellRenderer);
    TableColumn keyCol = table.getColumnModel().getColumn(1);
    keyCol.setPreferredWidth(200);
    keyCol.setCellRenderer(cellRenderer);
    TableColumn valuesCol = table.getColumnModel().getColumn(2);
    valuesCol.setPreferredWidth(300);
    valuesCol.setCellRenderer(cellRenderer);
    TableColumn envReplaceCol = table.getColumnModel().getColumn(3);
    envReplaceCol.setPreferredWidth(75);
    envReplaceCol.setCellRenderer(cellRenderer);

    table.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && DefaultPropView.this.table.getSelectedRow() != -1) {
                int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition());
                String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state);
                Metadata staticMet = state.getSelected().getModel().getStaticMetadata();
                override.setVisible(staticMet == null || !staticMet.containsKey(key));
                delete.setVisible(staticMet != null && staticMet.containsKey(key));
                tableMenu.show(DefaultPropView.this.table, e.getX(), e.getY());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });

    return table;
}

From source file:org.hibernate.search.demo.SearchDemo.java

private void initWidgets() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setDefaultLookAndFeelDecorated(true);

    BorderLayout borderLayout = new BorderLayout();
    getContentPane().setLayout(borderLayout);

    // the main table
    model = new DefaultTableModel(headers, 0) {
        public boolean isCellEditable(int row, int column) {
            // at the moment only allows the editing of the title
            return column == 2;
        }/*  www  .  j a  va  2 s  .c  o  m*/
    };
    modelListener = new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel) e.getSource();
            Object data = model.getValueAt(row, column);
            EntityManager em = emf.createEntityManager();
            updateTitle((Long) model.getValueAt(row, 0), (String) data);
            log.info("new value: {}", data);
        }
    };
    model.addTableModelListener(modelListener);
    final JTable table = new JTable(model);

    table.setFont(new Font("Courier New", Font.PLAIN, 14));
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);

    // build  the controls
    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new FlowLayout());

    final JTextField searchField = new JTextField(30);
    controlPanel.add(searchField);

    JButton searchButton = new JButton("Search");
    searchButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            List<Product> products;

            try {
                products = search(searchField.getText());
            } catch (ParseException pe) {
                JOptionPane.showMessageDialog(null, pe.getMessage(), "alert", JOptionPane.ERROR_MESSAGE);
                return;
            }

            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.removeTableModelListener(modelListener);
            model.setRowCount(0);
            for (int i = 0; i < products.size(); i++) {
                Object[] data = new Object[headers.length];
                Product p = products.get(i);
                data[0] = p.getProductId();
                data[1] = p.getASIN();
                data[2] = p.getTitle();
                //data[3] = p.getDescription();
                String actors = "";
                for (Actor actor : p.getActors()) {
                    actors = actors + actor.getName() + ", ";
                }
                data[3] = actors.length() == 0 ? actors : actors.substring(0, actors.length() - 2);
                String categories = "";
                for (Category category : p.getCategories()) {
                    categories = categories + category.getName() + ", ";
                }
                data[4] = categories.length() == 0 ? categories
                        : categories.substring(0, categories.length() - 2);
                model.insertRow(i, data);
            }
            model.addTableModelListener(modelListener);
        }
    });
    controlPanel.add(searchButton);

    JButton indexButton = new JButton("Index");
    indexButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            index();
        }
    });
    controlPanel.add(indexButton);

    JButton purgeButton = new JButton("Purge");
    purgeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            purge();
        }
    });
    controlPanel.add(purgeButton);

    getContentPane().add(controlPanel, BorderLayout.NORTH);
    getRootPane().setDefaultButton(searchButton);

    setSize(800, 200);
    setVisible(true);
}

From source file:org.nuclos.client.ui.collect.CollectController.java

/**
 * fills the result panel with the results from the current search.
 * @param lstclct List<Collectable>: the results from the current search.
 * @param iTotalNumberOfRecords The total number of records found. If the result was truncated, this is higher
 * than lstclct.size().//from w ww.j  av a 2  s. c  o m
 * @precondition iTotalNumberOfRecords >= lstclct.size()
 *
 * TODO: Make this protected again.
 */
public final void fillResultPanel(final List<Clct> lstclct, int iTotalNumberOfRecords, boolean bSortInitially) {
    if (iTotalNumberOfRecords < lstclct.size()) {
        throw new IllegalArgumentException("iTotalNumberOfRecords");
    }
    final boolean bResultTruncated = (iTotalNumberOfRecords > lstclct.size());

    final SortableCollectableTableModel<Clct> tblmodel = getResultTableModel();
    tblmodel.setCollectables(lstclct);
    if (bSortInitially) {
        tblmodel.sort();
    }

    final JTable tblResult = getResultTable();

    //setColumnWidths(tblResult);

    // set collect navigation model (for navigation buttons):
    if (navigationmodel != null)
        navigationmodel.removeChangeListener(navigationChangeListener);
    navigationmodel = new CollectNavigationModel(tblResult.getModel(), tblResult.getSelectionModel());
    navigationmodel.addChangeListener(navigationChangeListener);

    ctlResult.setStatusBar(tblResult, bResultTruncated, iTotalNumberOfRecords);

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            if (!lstclct.isEmpty()) {
                tblResult.getSelectionModel().setSelectionInterval(0, 0);
            }
        }
    });
}