Example usage for javax.swing.table DefaultTableCellRenderer DefaultTableCellRenderer

List of usage examples for javax.swing.table DefaultTableCellRenderer DefaultTableCellRenderer

Introduction

In this page you can find the example usage for javax.swing.table DefaultTableCellRenderer DefaultTableCellRenderer.

Prototype

public DefaultTableCellRenderer() 

Source Link

Document

Creates a default table cell renderer.

Usage

From source file:TableRenderDemo.java

public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    // Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

    // Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
}

From source file:cz.muni.fi.javaseminar.kafa.bookregister.gui.MainWindow.java

private void initBooksTable() {
    booksTable.getColumnModel().getColumn(2)
            .setCellEditor(new DatePickerCellEditor(new SimpleDateFormat("dd. MM. yyyy")));
    booksTable.getColumnModel().getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {

        @Override/*from  ww  w  .j av  a 2  s .  co  m*/
        public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected,
                boolean hasFocus, int row, int column) {

            if (value instanceof Date) {

                // You could use SimpleDateFormatter instead
                value = new SimpleDateFormat("dd. MM. yyyy").format(value);

            }

            return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

        }
    });
    booksTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    JPopupMenu booksPopupMenu = new JPopupMenu();
    JMenuItem deleteBook = new JMenuItem("Delete");
    booksPopupMenu.addPopupMenuListener(new PopupMenuListener() {

        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    int rowAtPoint = booksTable.rowAtPoint(
                            SwingUtilities.convertPoint(booksPopupMenu, new Point(0, 0), booksTable));
                    if (rowAtPoint > -1) {
                        booksTable.setRowSelectionInterval(rowAtPoint, rowAtPoint);
                    }
                }
            });
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
            // TODO Auto-generated method stub

        }
    });
    deleteBook.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (booksTable.getSelectedRow() == -1) {
                JOptionPane.showMessageDialog(MainWindow.this, "You haven't selected any book.");
                return;
            }
            Book book = booksTableModel.getBooks().get(booksTable.getSelectedRow());
            new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    log.debug("Deleting book: " + book.getName() + " from database.");
                    bookManager.deleteBook(book);
                    return null;
                }

                @Override
                protected void done() {
                    try {
                        get();
                    } catch (Exception e) {
                        log.error("There was an exception thrown while deleting a book.", e);
                        return;
                    }

                    updateModel();
                }

            }.execute();

        }
    });
    booksPopupMenu.add(deleteBook);
    booksTable.setComponentPopupMenu(booksPopupMenu);
}

From source file:components.TableRenderDemo.java

public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));

    //Set up tool tips for the sport cells.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
}

From source file:au.com.jwatmuff.eventmanager.util.GUIUtils.java

public static void leftAlignTable(JTable table) {
    Enumeration<TableColumn> cols = table.getColumnModel().getColumns();
    while (cols.hasMoreElements()) {
        TableColumn col = cols.nextElement();
        final TableCellRenderer oldRenderer = col.getCellRenderer();
        if (oldRenderer == null) {
            col.setCellRenderer(new DefaultTableCellRenderer() {
                @Override//from  ww w.  j  av a 2  s . c o  m
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                            column);
                    if (c instanceof JLabel) {
                        ((JLabel) c).setHorizontalAlignment(SwingConstants.LEFT);
                    }
                    return c;
                }
            });
        } else {
            col.setCellRenderer(new TableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    Component c = oldRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                            row, column);
                    if (c instanceof JLabel) {
                        ((JLabel) c).setHorizontalAlignment(SwingConstants.LEFT);
                    }
                    return c;
                }
            });
        }
    }
}

From source file:edu.ku.brc.specify.plugins.sgr.SGRResultsDisplay.java

/**
 * @return/*from   www  .  j  av a  2  s.  com*/
 */
private DefaultTableCellRenderer getTableCellRenderer() {
    return new DefaultTableCellRenderer() {
        @SuppressWarnings("unchecked")
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            //                DataObjTableModelRowInfo rowInfo = rowInfoList.get(row);

            boolean doCenter = false;
            Object val = value;
            if (value instanceof Pair<?, ?>) {
                Pair<Object, Object> pair = (Pair<Object, Object>) value;
                val = pair.first;
                doCenter = true;
            }

            JLabel lbl = (JLabel) super.getTableCellRendererComponent(table, val, isSelected, hasFocus, row,
                    column);
            //                if (rowInfo.isMainRecord())
            //                {
            //                    lbl.setForeground(Color.WHITE);
            //                    lbl.setBackground(Color.BLUE.brighter().brighter());
            //                    
            //                } else
            //                {
            //                    lbl.setForeground(model.isSame(column) ? sameColor : Color.BLACK);
            //                    lbl.setBackground(Color.WHITE);
            //                }
            lbl.setHorizontalTextPosition(doCenter ? SwingConstants.CENTER : SwingConstants.LEFT);

            return lbl;
        }
    };
}

From source file:se.backede.jeconomix.forms.report.SingleTransactionReport.java

public void filter() {

    companyComboBox.setEnabled(false);//www .j a  v  a 2  s .  c om
    yearComboBox.setEnabled(false);
    monthComboBox.setEnabled(false);

    LinkedList<TransactionDto> allTrasactions = new LinkedList<TransactionDto>(reports.getTransctions());

    CompanyDto company = (CompanyDto) companyComboBox.getSelectedItem();

    String yearString = (String) yearComboBox.getSelectedItem();
    Integer year = Integer.parseInt("0");
    if (yearString != null) {
        if (!yearString.equals(ALL_YEARS)) {
            year = Integer.parseInt(yearString);
        }
    }

    String monthString = (String) monthComboBox.getSelectedItem();
    Month month = null;
    if (monthString != null) {
        if (!monthString.equals(ALL_MONTHS)) {
            month = Month.valueOf(monthString);
        }
    }

    LinkedList<TransactionDto> filteredCompanies = new LinkedList<>(reports.getTransctions());

    if (company != null) {
        if (!company.getName().equals(ALL_COMPANIES)) {
            filteredCompanies = allTrasactions.stream().filter(line -> line.getCompany().equals(company))
                    .collect(Collectors.toCollection(LinkedList::new));
        }
    }

    LinkedList<TransactionDto> filteredByYear = (LinkedList) filteredCompanies.clone();
    if (yearString != null) {
        if (!yearString.equals(ALL_YEARS)) {
            for (TransactionDto filteredTransaction : filteredCompanies) {
                if (!Objects.equals(filteredTransaction.getBudgetYear(), year)) {
                    filteredByYear.remove(filteredTransaction);
                }
            }
        }
    }

    LinkedList<TransactionDto> filteredByMonth = (LinkedList) filteredByYear.clone();
    if (monthString != null) {
        if (!monthString.equals(ALL_MONTHS)) {
            for (TransactionDto filteredTransaction : filteredByYear) {
                if (filteredTransaction.getBudgetMonth() != month) {
                    filteredByMonth.remove(filteredTransaction);
                }
            }
        }
    }

    DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();

    rightRenderer.setHorizontalAlignment(JLabel.RIGHT);

    TransactionCompanyModel transModel = new TransactionCompanyModel(new HashSet<>(filteredByMonth));

    transactionTable.setModel(transModel);

    transactionTable.getColumnModel().getColumn(2).setCellRenderer(rightRenderer);

    transactionSumLabel.setText(transModel.getSum().toString().concat(" Kr"));
    categoryNameLabel.setText(reports.getCategory());

    companyComboBox.setEnabled(true);
    yearComboBox.setEnabled(true);
    monthComboBox.setEnabled(true);

}

From source file:com.diversityarrays.kdxplore.trials.SampleGroupViewer.java

private SampleGroupViewer(String title, KdxploreDatabase kdxdb, Trial trial, SampleGroup sampleGroup) {
    super(new BorderLayout());

    this.title = title;
    //        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    this.kdxdb = kdxdb;
    this.trial = trial;
    this.sampleGroup = sampleGroup;

    initialise();/*w  w  w.  j ava  2 s  .co m*/
    if (plotInfoByPlotId.isEmpty()) {
        add(new JLabel("No Plots available"), BorderLayout.CENTER);
    } else {
        tiChoiceTableModel = new TraitInstanceChoiceTableModel();
        JTable tiTable = new JTable(tiChoiceTableModel);
        tiTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    List<Integer> modelRows = GuiUtil.getSelectedModelRows(tiTable);
                    if (modelRows.isEmpty()) {
                        Point pt = e.getPoint();
                        int vrow = tiTable.rowAtPoint(pt);
                        if (vrow >= 0) {
                            int mrow = tiTable.convertRowIndexToModel(vrow);
                            if (mrow >= 0) {
                                showPopupMenu(tiTable, pt, Arrays.asList(Integer.valueOf(mrow)));
                            }
                        }
                    } else {
                        showPopupMenu(tiTable, e.getPoint(), modelRows);
                    }
                }
            }
        });

        tableModel = new DataTableModel(plotInfoByPlotId);
        JTable table = new JTable(tableModel);
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(SwingConstants.CENTER);
        table.setDefaultRenderer(String.class, r);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tiTable),
                new JScrollPane(table));
        splitPane.setResizeWeight(0.2);
        add(splitPane, BorderLayout.CENTER);
        table.setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(table, true));
    }
}

From source file:edu.harvard.i2b2.patientMapping.ui.PatientMappingJPanel.java

/** Creates new form PatientMappingJPanel */
public PatientMappingJPanel(java.awt.Container oAwtContainer) {
    columns = new ArrayList<SiteColumnData>();

    initComponents();/*from   ww w .jav a2s.  c o m*/
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    //model.addColumn("addedColumn1");
    //model.addColumn("addedColumn2");

    String[] columns = new String[3];
    columns[0] = new String("HIVE");
    columns[1] = new String("");
    columns[2] = new String("");
    //columns[3] = new String("");
    DefaultTableModel model1 = new DefaultTableModel(columns, 100);
    jTable1.setModel(model1);
    jTable1.setCellSelectionEnabled(true);
    TableColumn col = jTable1.getColumnModel().getColumn(0);
    DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
    dtcr.setHorizontalAlignment(SwingConstants.CENTER);
    col.setCellRenderer(dtcr);
    //jTable1.setCellSelectionEnabled(false);
    //model.setRowCount(100);
    //model.setValueAt(235600004, 0, 4);
    //model.setValueAt(235600005, 1, 5);
    //model.setValueAt(235600006, 5, 4);
    //model.setValueAt(235600007, 5, 5);
    //model.setValueAt(235600008, 6, 5);

    thisPanel = this;
    parent = oAwtContainer;

    //this.jLeftButton.setEnabled(false);
    this.jRightButton.setEnabled(false);
    this.jStartTextField.setEditable(false);
    this.jIncrementTextField.setEditable(false);
    //jAutoSaveCheckBox.setSelected(true);
}

From source file:dbseer.gui.user.DBSeerDataSet.java

public DBSeerDataSet() {
    live = new Boolean(false);
    Boolean[] trueFalse = { Boolean.TRUE, Boolean.FALSE };
    JComboBox trueFalseBox = new JComboBox(trueFalse);
    final DefaultCellEditor dce = new DefaultCellEditor(trueFalseBox);

    uniqueVariableName = "dataset_" + UUID.randomUUID().toString().replace('-', '_');
    uniqueModelVariableName = "mv_" + UUID.randomUUID().toString().replace('-', '_');
    name = "Unnamed dataset";
    tableModel = new DBSeerDataSetTableModel(null, new String[] { "Name", "Value" }, true);
    tableModel.addTableModelListener(this);
    table = new JTable(tableModel) {
        @Override//w  w  w .  jav a 2  s . co m
        public TableCellEditor getCellEditor(int row, int col) {
            if ((row == DBSeerDataSet.TYPE_USE_ENTIRE_DATASET
                    || row > TYPE_NUM_TRANSACTION_TYPE + numTransactionTypes) && col == 1)
                return dce;
            return super.getCellEditor(row, col);
        }
    };
    DefaultTableCellRenderer customRenderder = new DefaultTableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable jTable, Object o, boolean b, boolean b2, int row,
                int col) {
            Component cell = super.getTableCellRendererComponent(jTable, o, b, b2, row, col);
            if (row == DBSeerDataSet.TYPE_START_INDEX || row == DBSeerDataSet.TYPE_END_INDEX) {
                if (((Boolean) table.getValueAt(DBSeerDataSet.TYPE_USE_ENTIRE_DATASET, 1))
                        .booleanValue() == true) {
                    cell.setForeground(Color.LIGHT_GRAY);
                } else {
                    cell.setForeground(Color.BLACK);
                }
            } else if (row == DBSeerDataSet.TYPE_NUM_TRANSACTION_TYPE) {
                cell.setForeground(Color.LIGHT_GRAY);
            } else {
                cell.setForeground(Color.BLACK);
            }
            return cell;
        }
    };
    table.getColumnModel().getColumn(0).setCellRenderer(customRenderder);
    table.getColumnModel().getColumn(1).setCellRenderer(customRenderder);

    table.setFillsViewportHeight(true);
    table.getColumnModel().getColumn(0).setMaxWidth(400);
    table.getColumnModel().getColumn(0).setPreferredWidth(300);
    table.getColumnModel().getColumn(1).setPreferredWidth(600);
    table.setRowHeight(20);

    this.useEntireDataSet = true;
    for (String header : tableHeaders) {
        if (header.equalsIgnoreCase("Use Entire DataSet"))
            tableModel.addRow(new Object[] { header, Boolean.TRUE });
        else
            tableModel.addRow(new Object[] { header, "" });
    }

    for (int i = 0; i < numTransactionTypes; ++i) {
        tableModel.addRow(new Object[] { "Name of Transaction Type " + (i + 1), "Type " + (i + 1) });
        DBSeerTransactionType type = new DBSeerTransactionType("Type " + (i + 1), true);
        transactionTypes.add(type);
    }

    for (int i = 0; i < transactionTypes.size(); ++i) {
        DBSeerTransactionType txType = transactionTypes.get(i);
        if (txType.isEnabled()) {
            tableModel.addRow(new Object[] { "Use Transaction Type " + (i + 1), Boolean.TRUE });
        } else {
            tableModel.addRow(new Object[] { "Use Transaction Type " + (i + 1), Boolean.FALSE });
        }
    }

    this.updateTable();
    dataSetLoaded = false;
    isCurrent = false;

    tableModel.setUseEntireDataSet(this.useEntireDataSet.booleanValue());
}

From source file:net.sf.profiler4j.console.ProjectDialog.java

/**
 * This method initializes rulesTable/*from   w ww  .j a v a2  s  .co m*/
 * 
 * @return javax.swing.JTable
 */
private JTable getRulesTable() {
    if (rulesTable == null) {
        rulesTable = new JTable();
        rulesTable.setModel(ruleTableModel);
        rulesTable.setRowMargin(4);
        rulesTable.setRowHeight(24);
        rulesTable.setFont(new Font("Monospaced", Font.PLAIN, 14));
        TableColumn c;

        c = rulesTable.getColumnModel().getColumn(0);
        c.setMinWidth(300);

        c = rulesTable.getColumnModel().getColumn(1);
        c.setMinWidth(80);
        c.setMaxWidth(80);

        JComboBox editorCb = new JComboBox();
        for (Rule.Action a : Rule.Action.values()) {
            editorCb.addItem(a);
        }
        c.setCellEditor(new DefaultCellEditor(editorCb));
        c.setCellRenderer(new DefaultTableCellRenderer() {
            Font font = new Font("Monospaced", Font.BOLD, 13);

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                Rule.Action r = (Rule.Action) value;
                setHorizontalAlignment(CENTER);
                setFont(font);
                if (r == Rule.Action.ACCEPT) {
                    setBackground(Color.GREEN);
                } else {
                    setBackground(Color.RED);
                }
                if (isSelected) {
                    setForeground(Color.YELLOW);
                } else {
                    setForeground(Color.BLACK);
                }
                return this;
            }
        });

    }
    return rulesTable;
}