Example usage for javax.swing.table JTableHeader setDefaultRenderer

List of usage examples for javax.swing.table JTableHeader setDefaultRenderer

Introduction

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

Prototype

public void setDefaultRenderer(TableCellRenderer defaultRenderer) 

Source Link

Document

Sets the default renderer to be used when no headerRenderer is defined by a TableColumn.

Usage

From source file:com.mirth.connect.client.ui.components.MirthTreeTable.java

public MirthTreeTable(String prefix, Set<String> defaultVisibleColumns) {
    customHiddenColumnMap = new HashMap<String, Set<String>>();

    this.prefix = prefix;
    this.defaultVisibleColumns = defaultVisibleColumns;

    columnOrderMap = new HashMap<String, Integer>();
    sortOrderColumn = -1;//from  w  w  w . jav  a 2 s  .co m
    sortOrder = null;

    if (StringUtils.isNotEmpty(prefix)) {
        try {
            userPreferences = Preferences.userNodeForPackage(Mirth.class);
            String columns = userPreferences.get(prefix + "ColumnOrderMap", "");

            if (StringUtils.isNotEmpty(columns)) {
                columnOrderMap = (Map<String, Integer>) ObjectXMLSerializer.getInstance().deserialize(columns,
                        Map.class);
            }
        } catch (Exception e) {
        }

        try {
            String order = userPreferences.get(prefix + "SortOrder", "");

            if (StringUtils.isNotEmpty(order)) {
                sortOrder = ObjectXMLSerializer.getInstance().deserialize(order, SortOrder.class);
                sortOrderColumn = userPreferences.getInt(prefix + "SortOrderColumn", -1);
            }
        } catch (Exception e) {
        }
    }

    addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent e) {
            boolean isAccelerated = (((e.getModifiers()
                    & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) > 0)
                    || ((e.getModifiers() & InputEvent.CTRL_MASK) > 0));
            if ((e.getKeyCode() == KeyEvent.VK_S) && isAccelerated) {
                PlatformUI.MIRTH_FRAME.doContextSensitiveSave();
            }
        }

        public void keyReleased(KeyEvent e) {
        }

        public void keyTyped(KeyEvent e) {
        }
    });

    /*
     * Swingx 1.0 has this set to true by default, which doesn't allow dragging and dropping
     * into tables. Swingx 0.8 had this set to false. Tables that want it set to true can
     * override it.
     */
    putClientProperty("terminateEditOnFocusLost", Boolean.FALSE);

    JTableHeader header = getTableHeader();
    header.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent e) {
            saveColumnOrder();
        }
    });
    header.setDefaultRenderer(new SortableHeaderCellRenderer(header.getDefaultRenderer()));

    final JButton columnControlButton = new JButton(new ColumnControlButton(this).getIcon());

    columnControlButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JPopupMenu columnMenu = getColumnMenu();
            Dimension buttonSize = columnControlButton.getSize();
            int xPos = columnControlButton.getComponentOrientation().isLeftToRight()
                    ? buttonSize.width - columnMenu.getPreferredSize().width
                    : 0;
            columnMenu.show(columnControlButton, xPos, columnControlButton.getHeight());
        }

    });

    setColumnControl(columnControlButton);
}

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

public TrialViewPanel(WindowOpener<JFrame> windowOpener, OfflineData od,
        Transformer<Trial, Boolean> checkIfEditorActive, Consumer<Trial> onTraitInstancesRemoved,
        MessagePrinter mp) {/*from ww  w  .j  a va2s.com*/
    super(new BorderLayout());

    this.windowOpener = windowOpener;
    this.checkIfEditorActive = checkIfEditorActive;
    this.onTraitInstancesRemoved = onTraitInstancesRemoved;
    this.messagePrinter = mp;

    this.offlineData = od;
    this.offlineData.addOfflineDataChangeListener(offlineDataChangeListener);
    KdxploreDatabase db = offlineData.getKdxploreDatabase();
    if (db != null) {
        db.addEntityChangeListener(trialChangeListener);
    }

    trialDataTable.setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(trialDataTable, true));
    trialPropertiesTable
            .setTransferHandler(TableTransferHandler.initialiseForCopySelectAll(trialPropertiesTable, true));

    // Note: Can't use renderers because the TM always returns String.class
    // for getColumnClass()
    // trialPropertiesTable.setDefaultRenderer(TrialLayout.class, new
    // TrialLayoutRenderer(trialPropertiesTableModel));
    // trialPropertiesTable.setDefaultRenderer(PlotIdentOption.class, new
    // PlotIdentOptionRenderer(trialPropertiesTableModel));

    trialPropertiesTableModel.addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent e) {
            if (trialPropertiesTableModel.getRowCount() > 0) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        GuiUtil.initialiseTableColumnWidths(trialPropertiesTable);
                    }
                });
                trialPropertiesTableModel.removeTableModelListener(this);
            }
        }
    });

    //      int tnsColumnIndex = -1;
    //      for (int col = trialPropertiesTableModel.getColumnCount(); --col >= 0; ) {
    //         if (TraitNameStyle.class == trialPropertiesTableModel.getColumnClass(col)) {
    //            tnsColumnIndex = col;
    //            break;
    //         }
    //      }

    editAction.setEnabled(false);
    trialPropertiesTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                int vrow = trialPropertiesTable.getSelectedRow();
                editAction.setEnabled(vrow >= 0 && trialPropertiesTableModel.isCellEditable(vrow, 1));
            }
        }
    });

    errorMessage.setForeground(Color.RED);
    Box top = Box.createHorizontalBox();
    top.add(errorMessage);
    top.add(Box.createHorizontalGlue());
    top.add(new JButton(editAction));

    JPanel main = new JPanel(new BorderLayout());
    main.add(new JScrollPane(trialPropertiesTable), BorderLayout.CENTER);
    main.add(legendPanel, BorderLayout.SOUTH);

    JScrollPane trialDataTableScrollPane = new JScrollPane(trialDataTable);

    // The preferred height of the viewport is determined
    // by whether or not we need to use hh:mm:ss in the name of any of
    // the scoring data sets.
    JViewport viewPort = new JViewport() {
        @Override
        public Dimension getPreferredSize() {
            Dimension d = super.getPreferredSize();
            d.height = 32;
            TableModel model = trialDataTable.getModel();
            if (model instanceof TrialData) {
                if (((TrialData) model).isUsingHMSformat()) {
                    d.height = 48;
                }
            }
            return d;
        }
    };
    trialDataTableScrollPane.setColumnHeader(viewPort);

    JTableHeader th = trialDataTable.getTableHeader();
    th.setDefaultRenderer(trialDataTableHeaderRenderer);
    th.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int column = th.columnAtPoint(e.getPoint());
            trialDataTableHeaderRenderer.columnSelected = column;
            boolean shifted = 0 != (MouseEvent.SHIFT_MASK & e.getModifiers());
            boolean right = SwingUtilities.isRightMouseButton(e);
            updateDeleteSamplesAction(shifted, right);
            e.consume();
        }
    });

    trialDataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                removeTraitInstancesAction.setEnabled(trialDataTable.getSelectedRowCount() > 0);
            }
        }
    });
    removeTraitInstancesAction.setEnabled(false);

    KDClientUtils.initAction(ImageId.PLUS_BLUE_24, addSampleGroupAction, Msg.TOOLTIP_ADD_SAMPLES_FOR_SCORING());
    KDClientUtils.initAction(ImageId.TRASH_24, deleteSamplesAction, Msg.TOOLTIP_DELETE_COLLECTED_SAMPLES());
    KDClientUtils.initAction(ImageId.EXPORT_24, exportSamplesAction, Msg.TOOLTIP_EXPORT_SAMPLES_OR_TRAITS());
    KDClientUtils.initAction(ImageId.MINUS_GOLD_24, removeTraitInstancesAction,
            Msg.TOOLTIP_REMOVE_TRAIT_INSTANCES_WITH_NO_DATA());

    JPanel trialDataPanel = new JPanel(new BorderLayout());
    Box buttons = Box.createHorizontalBox();

    buttons.add(new JButton(removeTraitInstancesAction));
    buttons.add(Box.createHorizontalGlue());
    buttons.add(new JButton(exportSamplesAction));
    buttons.add(Box.createHorizontalGlue());
    buttons.add(new JButton(addSampleGroupAction));
    buttons.add(Box.createHorizontalStrut(8));
    buttons.add(new JButton(deleteSamplesAction));
    trialDataPanel.add(GuiUtil.createLabelSeparator("Measurements by Source", buttons), BorderLayout.NORTH);
    trialDataPanel.add(trialDataTableScrollPane, BorderLayout.CENTER);

    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, main, trialDataPanel);
    splitPane.setResizeWeight(0.5);

    add(top, BorderLayout.NORTH);
    add(splitPane, BorderLayout.CENTER);

    trialDataTable.setDefaultRenderer(Object.class, new TrialDataCellRenderer());

    trialDataTable.addPropertyChangeListener("model", new PropertyChangeListener() {
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            trialDataTableHeaderRenderer.columnSelected = -1;
            updateDeleteSamplesAction(false, false);
        }
    });
}

From source file:com.itemanalysis.jmetrik.gui.Jmetrik.java

public Jmetrik() {
    super("jMetrik");
    setPreferredSize(new Dimension(1024, 650));
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    //properly close database if user closes window
    this.addWindowListener(new WindowAdapter() {
        @Override//from   ww w  .ja v a2 s.co  m
        public void windowClosing(WindowEvent we) {
            if (workspace != null) {
                workspace.closeDatabase();
            }
            System.exit(0);
        }
    });

    //add statusbar
    statusBar = new StatusBar(1024, 30);
    statusBar.setBorder(new EmptyBorder(2, 2, 2, 2));
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    //start logging
    startLog();

    //left-right splitpane
    JSplitPane splitPane1 = new JSplitPane();
    splitPane1.setDividerLocation(200);

    //setup workspace list
    workspaceList = new JList();
    workspaceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    workspaceList.setModel(new SortedListModel<DataTableName>());
    workspaceList.addKeyListener(new DeleteKeyListener());
    //        workspaceList.getInsets().set(5, 5, 5, 5);

    //add icon to list cell renderer
    String urlString = "/images/spreadsheet.png";
    URL url = this.getClass().getResource(urlString);
    final ImageIcon tableIcon = new ImageIcon(url, "Table");
    workspaceList.setCellRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected,
                    cellHasFocus);
            label.setIcon(tableIcon);
            return label;
        }
    });

    JScrollPane scrollPane1 = new JScrollPane(workspaceList);
    scrollPane1.setPreferredSize(new Dimension(200, 698));

    splitPane1.setLeftComponent(scrollPane1);

    //tabbed pane for top pane
    tabbedPane = new JTabbedPane();
    tabbedPane.setTabPlacement(JTabbedPane.BOTTOM);

    //setup data table
    dataTable = new DataTable();
    dataTable.setRowHeight(18);

    //change size of table header and center text
    JTableHeader header = dataTable.getTableHeader();
    header.setDefaultRenderer(new TableHeaderCellRenderer());

    JScrollPane dataScrollPane = new JScrollPane(dataTable);
    tabbedPane.addTab("Data", dataScrollPane);

    //setup variable table
    variableTable = new DataTable();
    variableTable.setRowHeight(18);
    variableTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);
            if (e.getClickCount() == 2) {
                JTable target = (JTable) e.getSource();
                int row = target.getSelectedRow();
                int col = target.getSelectedColumn();
                if (col == 0) {
                    if (target.getModel() instanceof VariableModel) {
                        VariableModel vModel = (VariableModel) target.getModel();
                        String s = (String) vModel.getValueAt(row, col);

                        DatabaseName db = workspace.getDatabaseName();
                        DataTableName table = workspace.getCurrentDataTable();

                        RenameVariableDialog renameVariableDialog = new RenameVariableDialog(Jmetrik.this, db,
                                table, s);
                        renameVariableDialog.setVisible(true);

                        if (renameVariableDialog.canRun()) {
                            RenameVariableCommand command = renameVariableDialog.getCommand();
                            workspace.runProcess(command);
                        }

                    } //end instanceof

                } //end if col==0

            } //end if click count==2
        }//end mouse clicked
    });

    //change size of table header and center text
    JTableHeader variableHeader = variableTable.getTableHeader();
    variableHeader.setDefaultRenderer(new TableHeaderCellRenderer());
    variableHeader.setPreferredSize(new Dimension(30, 21));

    JScrollPane variableScrollPane = new JScrollPane(variableTable);
    tabbedPane.addTab("Variables", variableScrollPane);

    splitPane1.setRightComponent(tabbedPane);
    getContentPane().add(splitPane1, BorderLayout.CENTER);

    //add status bar listener - needed to display status message that are generated within this class
    this.addPropertyChangeListener(statusBar.getStatusListener());

    //add listener for displaying error messages - needed to display errors and exceptions
    this.addPropertyChangeListener(new ErrorOccurredPropertyChangeListener());

    //instantiate file utilities
    fileUtils = new JmetrikFileUtils();
    fileUtils.addPropertyChangeListener(statusBar.getStatusListener());

    //set import and export path to user's documents folder
    JFileChooser chooser = new JFileChooser();
    FileSystemView fw = chooser.getFileSystemView();
    importExportPath = fw.getDefaultDirectory().toString().replaceAll("\\\\", "/");

    //create and start a workspace
    startWorkspace();

    //create menu bar and tool bar
    this.setJMenuBar(createMenuBar());

    JToolBar toolBar = createToolBar();
    toolBar.setFloatable(false);
    toolBar.setRollover(true);
    getContentPane().add(toolBar, BorderLayout.PAGE_START);

    pack();

}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

/**
 * sets up a modified renderer for the result table header that uses the HTML formatted toString() value of the
 * column's entity field rather than its unformatted getLabel() value.
 *//*from  w  w w .jav  a 2  s  .c  o m*/
private void setupResultTableHeaderRenderer() {
    final JTableHeader header = getResultTable().getTableHeader();
    final TableCellRenderer headerrendererDefault = header.getDefaultRenderer();
    header.setDefaultRenderer(new TableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable tbl, Object oValue, boolean bSelected,
                boolean bHasFocus, int iRow, int iColumn) {
            final CollectableEntityField f = GenericObjectCollectController.this.getResultTableModel()
                    .getCollectableEntityField(tbl.convertColumnIndexToModel(iColumn));
            final String value;
            if (f instanceof CollectableEOEntityField) {
                // In the pivot case, we want to separate the column name
                // from the tool top.
                final CollectableEOEntityField field = (CollectableEOEntityField) f;
                final EntityFieldMetaDataVO ef = field.getMeta();
                if (ef.getPivotInfo() != null) {
                    value = ef.getField() + ":" + ef.getPivotInfo().getValueField();
                } else {
                    value = f.getLabel();
                }
            } else {
                value = f.getLabel();
            }
            return headerrendererDefault.getTableCellRendererComponent(tbl, value, bSelected, bHasFocus, iRow,
                    iColumn);
        }
    });
}