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: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 . j a va2 s  .  c  om*/
        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.executequery.gui.browser.ConnectionPanel.java

private void init() {

    // ---------------------------------
    // create the basic props panel

    // initialise the fields
    nameField = createTextField();//from   w  ww .  j  av  a2s . c o  m
    passwordField = createPasswordField();
    hostField = createTextField();
    portField = createNumberTextField();
    sourceField = createMatchedWidthTextField();
    userField = createTextField();
    urlField = createMatchedWidthTextField();

    nameField.addFocusListener(new ConnectionNameFieldListener(this));

    savePwdCheck = ActionUtilities.createCheckBox("Store Password", "setStorePassword");
    encryptPwdCheck = ActionUtilities.createCheckBox("Encrypt Password", "setEncryptPassword");

    savePwdCheck.addActionListener(this);
    encryptPwdCheck.addActionListener(this);

    // retrieve the drivers
    buildDriversList();

    // ---------------------------------
    // add the basic connection fields

    TextFieldPanel mainPanel = new TextFieldPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    gbc.insets = new Insets(10, 10, 10, 10);
    gbc.gridy = 0;
    gbc.gridx = 0;

    statusLabel = new DefaultFieldLabel();
    addLabelFieldPair(mainPanel, "Status:", statusLabel, "Current connection status", gbc);

    gbc.insets.bottom = 5;
    addLabelFieldPair(mainPanel, "Connection Name:", nameField, "A friendly name for this connection", gbc);

    addLabelFieldPair(mainPanel, "User Name:", userField, "Login user name", gbc);

    addLabelFieldPair(mainPanel, "Password:", passwordField, "Login password", gbc);

    JButton showPassword = new LinkButton("Show Password");
    showPassword.setActionCommand("showPassword");
    showPassword.addActionListener(this);

    JPanel passwordOptionsPanel = new JPanel(new GridBagLayout());
    addComponents(passwordOptionsPanel,
            new ComponentToolTipPair[] {
                    new ComponentToolTipPair(savePwdCheck,
                            "Store the password with the connection information"),
                    new ComponentToolTipPair(encryptPwdCheck, "Encrypt the password when saving"),
                    new ComponentToolTipPair(showPassword, "Show the password in plain text") });

    gbc.gridy++;
    gbc.gridx = 1;
    gbc.weightx = 1.0;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    mainPanel.add(passwordOptionsPanel, gbc);

    addLabelFieldPair(mainPanel, "Host Name:", hostField, "Server host name or IP address", gbc);

    addLabelFieldPair(mainPanel, "Port:", portField, "Database port number", gbc);

    addLabelFieldPair(mainPanel, "Data Source:", sourceField, "Data source name", gbc);

    addLabelFieldPair(mainPanel, "JDBC URL:", urlField, "The full JDBC URL for this connection (optional)",
            gbc);

    addDriverFields(mainPanel, gbc);

    connectButton = createButton("Connect", CONNECT_ACTION_COMMAND, 'T');
    disconnectButton = createButton("Disconnect", "disconnect", 'D');

    JPanel buttons = new JPanel(new GridBagLayout());
    gbc.gridy++;
    gbc.gridx = 0;
    gbc.insets.top = 5;
    gbc.insets.left = 0;
    gbc.insets.right = 10;
    gbc.gridwidth = 1;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.anchor = GridBagConstraints.NORTHEAST;
    gbc.fill = GridBagConstraints.NONE;
    buttons.add(connectButton, gbc);
    gbc.gridx++;
    gbc.weightx = 0;
    buttons.add(disconnectButton, gbc);

    gbc.insets.right = 0;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    mainPanel.add(buttons, gbc);

    // ---------------------------------
    // create the advanced panel

    model = new JdbcPropertiesTableModel();
    JTable table = new DefaultTable(model);
    table.getTableHeader().setReorderingAllowed(false);

    TableColumnModel tcm = table.getColumnModel();

    TableColumn column = tcm.getColumn(2);
    column.setCellRenderer(new DeleteButtonRenderer());
    column.setCellEditor(new DeleteButtonEditor(table, new JCheckBox()));
    column.setMaxWidth(24);
    column.setMinWidth(24);

    JScrollPane scroller = new JScrollPane(table);

    // advanced jdbc properties
    JPanel advPropsPanel = new JPanel(new GridBagLayout());
    advPropsPanel.setBorder(BorderFactory.createTitledBorder("JDBC Properties"));
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.insets.top = 0;
    gbc.insets.left = 10;
    gbc.insets.right = 10;
    gbc.weighty = 0;
    gbc.weightx = 1.0;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    advPropsPanel.add(new DefaultFieldLabel("Enter any key/value pair properties for this connection"), gbc);
    gbc.gridy++;
    advPropsPanel.add(
            new DefaultFieldLabel("Refer to the relevant JDBC driver documentation for possible entries"), gbc);
    gbc.gridy++;
    gbc.insets.bottom = 10;
    gbc.weighty = 1.0;
    gbc.fill = GridBagConstraints.BOTH;
    advPropsPanel.add(scroller, gbc);

    // transaction isolation
    txApplyButton = WidgetFactory.createInlineFieldButton("Apply", "transactionLevelChanged");
    txApplyButton.setToolTipText("Apply this level to all open connections of this type");
    txApplyButton.setEnabled(false);
    txApplyButton.addActionListener(this);

    // add a dummy select value to the tx levels
    String[] txLevels = new String[Constants.TRANSACTION_LEVELS.length + 1];
    txLevels[0] = "Database Default";
    for (int i = 1; i < txLevels.length; i++) {
        txLevels[i] = Constants.TRANSACTION_LEVELS[i - 1];
    }
    txCombo = WidgetFactory.createComboBox(txLevels);

    JPanel advTxPanel = new JPanel(new GridBagLayout());
    advTxPanel.setBorder(BorderFactory.createTitledBorder("Transaction Isolation"));
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets.top = 0;
    gbc.insets.left = 10;
    gbc.insets.right = 10;
    gbc.insets.bottom = 5;
    gbc.weighty = 0;
    gbc.weightx = 1.0;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    advTxPanel.add(new DefaultFieldLabel("Default transaction isolation level for this connection"), gbc);
    gbc.gridy++;
    gbc.insets.bottom = 10;
    advTxPanel.add(
            new DefaultFieldLabel(
                    "Note: the selected isolation level " + "will apply to ALL open connections of this type."),
            gbc);
    gbc.gridy++;
    gbc.gridx = 0;
    gbc.gridwidth = 1;
    gbc.insets.top = 0;
    gbc.insets.left = 10;
    gbc.weightx = 0;
    advTxPanel.add(new DefaultFieldLabel("Isolation Level:"), gbc);
    gbc.gridx = 1;
    gbc.insets.left = 5;
    gbc.weightx = 1.0;
    gbc.insets.right = 5;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    advTxPanel.add(txCombo, gbc);
    gbc.gridx = 2;
    gbc.weightx = 0;
    gbc.insets.left = 0;
    gbc.insets.right = 10;
    advTxPanel.add(txApplyButton, gbc);

    JPanel advancedPanel = new JPanel(new BorderLayout());
    advancedPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    advancedPanel.add(advPropsPanel, BorderLayout.CENTER);
    advancedPanel.add(advTxPanel, BorderLayout.SOUTH);

    JScrollPane scrollPane = new JScrollPane(mainPanel);
    scrollPane.setBorder(null);

    sshTunnelConnectionPanel = new SSHTunnelConnectionPanel();

    tabPane = new JTabbedPane(JTabbedPane.BOTTOM);
    tabPane.addTab("Basic", scrollPane);
    tabPane.addTab("Advanced", advancedPanel);
    tabPane.addTab("SSH Tunnel", sshTunnelConnectionPanel);

    tabPane.addChangeListener(this);

    add(tabPane, BorderLayout.CENTER);

    EventMediator.registerListener(this);
}

From source file:org.isatools.isacreator.gui.formelements.SubForm.java

protected void setHeaderProperties(JTable table, TableCellRenderer renderer) {

    Enumeration<TableColumn> columns = table.getColumnModel().getColumns();
    while (columns.hasMoreElements()) {
        columns.nextElement().setHeaderRenderer(renderer);
    }/*from   w  ww. j ava 2  s  .  c om*/
}

From source file:org.isatools.isacreator.spreadsheet.Spreadsheet.java

/**
 * Setup the JTable with its desired characteristics
 *//* ww w.  j a  va  2s  .  c om*/
private void setupTable() {
    table = new CustomTable(spreadsheetModel);
    table.setShowGrid(true);
    table.setGridColor(Color.BLACK);
    table.setShowVerticalLines(true);
    table.setShowHorizontalLines(true);
    table.setGridColor(UIHelper.LIGHT_GREEN_COLOR);
    table.setRowSelectionAllowed(true);
    table.setColumnSelectionAllowed(true);
    table.setAutoCreateColumnsFromModel(false);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.getSelectionModel().addListSelectionListener(this);
    table.getColumnModel().getSelectionModel().addListSelectionListener(this);
    table.getTableHeader().setReorderingAllowed(true);
    table.getColumnModel().addColumnModelListener(this);
    try {
        table.setDefaultRenderer(Class.forName("java.lang.Object"), new SpreadsheetCellRenderer());
    } catch (ClassNotFoundException e) {
        // ignore this error
    }

    table.addMouseListener(this);
    table.getTableHeader().addMouseMotionListener(new MouseMotionListener() {
        public void mouseDragged(MouseEvent event) {
        }

        public void mouseMoved(MouseEvent event) {
            // display a tooltip when user hovers over a column. tooltip is derived
            // from the description of a field from the TableReferenceObject.
            JTable table = ((JTableHeader) event.getSource()).getTable();
            TableColumnModel colModel = table.getColumnModel();
            int colIndex = colModel.getColumnIndexAtX(event.getX());

            // greater than 1 to account for the row no. being the first col
            if (colIndex >= 1) {
                TableColumn tc = colModel.getColumn(colIndex);
                if (tc != null) {
                    try {
                        table.getTableHeader().setToolTipText(getFieldDescription(tc));
                    } catch (Exception e) {
                        // ignore this error
                    }
                }
            }
        }
    });

    //table.getColumnModel().addColumnModelListener(this);
    InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke tab = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);

    //  Override the default tab behaviour
    //  Tab to the next editable cell. When no editable cells goto next cell.
    final Action previousTabAction = table.getActionMap().get(im.get(tab));
    Action newTabAction = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            // maintain previous tab action procedure
            previousTabAction.actionPerformed(e);

            JTable table = (JTable) e.getSource();
            int row = table.getSelectedRow();
            int originalRow = row;
            int column = table.getSelectedColumn();
            int originalColumn = column;

            while (!table.isCellEditable(row, column)) {
                previousTabAction.actionPerformed(e);
                row = table.getSelectedRow();
                column = table.getSelectedColumn();

                //  Back to where we started, get out.
                if ((row == originalRow) && (column == originalColumn)) {
                    break;
                }
            }

            if (table.editCellAt(row, column)) {
                table.getEditorComponent().requestFocusInWindow();
            }
        }
    };

    table.getActionMap().put(im.get(tab), newTabAction);
    TableColumnModel model = table.getColumnModel();

    String previousColumnName = null;
    for (int columnIndex = 0; columnIndex < tableReferenceObject.getHeaders().size(); columnIndex++) {
        if (!model.getColumn(columnIndex).getHeaderValue().toString()
                .equals(TableReferenceObject.ROW_NO_TEXT)) {
            model.getColumn(columnIndex).setHeaderRenderer(columnRenderer);
            model.getColumn(columnIndex).setPreferredWidth(spreadsheetFunctions
                    .calcColWidths(model.getColumn(columnIndex).getHeaderValue().toString()));
            // add appropriate cell editor for cell.
            spreadsheetFunctions.addCellEditor(model.getColumn(columnIndex), previousColumnName);
            previousColumnName = model.getColumn(columnIndex).getHeaderValue().toString();
        } else {
            model.getColumn(columnIndex).setHeaderRenderer(new RowNumberCellRenderer());
        }
    }

    JTableHeader header = table.getTableHeader();
    header.setBackground(UIHelper.BG_COLOR);
    header.addMouseListener(new HeaderListener(header, columnRenderer));

    table.addNotify();
}

From source file:org.lockss.devtools.plugindef.EDPInspectorTableModel.java

public void setColumnSize(JTable table, int col) {
    TableColumn column = null;//  w  ww  .jav a 2 s  .  c o m
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    String longestStr = "";
    String curString = "";

    for (int row = 0; row < inspectorEntries.length; row++) {
        curString = data[row][col].toString();
        if (curString.length() > longestStr.length()) {
            longestStr = curString;
        }
    }
    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

    column = table.getColumnModel().getColumn(col);

    comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
    headerWidth = comp.getPreferredSize().width;

    comp = table.getDefaultRenderer(getColumnClass(col)).getTableCellRendererComponent(table, longestStr, false,
            false, 0, col);
    cellWidth = comp.getPreferredSize().width;

    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}

From source file:org.ngrinder.recorder.ui.RecordingControlPanel.java

protected JTable createFilterTables(ConnectionFilter connectionFilter) {
    final FilterTableModel dm = new FilterTableModel(connectionFilter);
    JTable jTable = new JTable(dm);
    TableColumnModel columnModel = jTable.getColumnModel();
    setColumnWidth(columnModel.getColumn(0), 30, 30, 30);
    setColumnWidth(columnModel.getColumn(2), 30, 50, 30);
    jTable.setRowSorter(new TableRowSorter<TableModel>(dm));
    createUpdateCheckScheduledTask(dm);/*from   w  w w  .ja  v a 2s .co  m*/
    return jTable;
}

From source file:org.nuclos.client.main.MainController.java

private Map<String, Map<String, Action>> getCommandMap() {
    HashMap<String, Map<String, Action>> res = new HashMap<String, Map<String, Action>>();
    HashMap<String, Action> mainController = new HashMap<String, Action>();

    /* that's too cumbersome:
    mainController.put(/*w  w w. ja v  a 2s  .c  o m*/
       "cmdChangePassword",
       new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
       cmdChangePassword();
    }
       });
     */

    mainController.put("cmdDirectHelp", cmdDirectHelp);
    mainController.put("cmdShowPersonalTasks", cmdShowPersonalTasks);
    mainController.put("cmdShowTimelimitTasks", cmdShowTimelimitTasks);
    mainController.put("cmdShowPersonalSearchFilters", cmdShowPersonalSearchFilters);
    mainController.put("cmdChangePassword", cmdChangePassword);
    mainController.put("cmdOpenSettings", cmdOpenSettings);
    mainController.put("cmdOpenManagementConsole", cmdOpenManagementConsole);
    //mainController.put("cmdOpenEntityWizard", cmdOpenEntityWizard);
    mainController.put("cmdOpenRelationEditor", cmdOpenRelationEditor);
    mainController.put("cmdOpenCustomComponentWizard", cmdOpenCustomComponentWizard);
    //mainController.put("cmdRefreshClientCaches", cmdRefreshClientCaches);
    mainController.put("cmdSelectAll", cmdSelectAll);
    mainController.put("cmdHelpContents", cmdHelpContents);
    mainController.put("cmdShowAboutDialog", cmdShowAboutDialog);
    mainController.put("cmdShowProjectReleaseNotes", cmdShowProjectReleaseNotes);
    mainController.put("cmdShowNuclosReleaseNotes", cmdShowNuclosReleaseNotes);
    mainController.put("cmdLogoutExit", cmdLogoutExit);
    mainController.put("cmdWindowClosing", cmdWindowClosing);
    mainController.put("cmdExecuteRport", cmdExecuteRport);

    for (Method m : getClass().getDeclaredMethods()) {
        if (m.getName().startsWith("cmd")) {
            Class<?>[] pt = m.getParameterTypes();
            if (pt.length == 0 || (pt.length == 1 && pt[0].isAssignableFrom(ActionEvent.class))) {
                final Method fm = m;
                Action a = new AbstractAction(m.getName()) {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        miDelegator(e, fm);
                    }
                };
                mainController.put(m.getName(), a);
            }
        }
    }

    res.put("MainController", mainController);

    HashMap<String, Action> clipboardUtils = new HashMap<String, Action>();
    clipboardUtils.put("cutAction", new ClipboardUtils.CutAction());
    clipboardUtils.put("copyAction", new ClipboardUtils.CopyAction());
    clipboardUtils.put("pasteAction", new ClipboardUtils.PasteAction());

    res.put("ClipboardUtils", clipboardUtils);

    HashMap<String, Action> dev = new HashMap<String, Action>();
    dev.put("jmsNotification", new AbstractAction("Test JMS notification") {

        @Override
        public void actionPerformed(ActionEvent e) {
            String s = JOptionPane.showInputDialog(getMainFrame(), "Topic: Message");
            if (s == null)
                return;
            String[] a = s.split(": *");
            if (a.length == 2) {
                // testFacadeRemote.testClientNotification(a[0], a[1]);
                throw new UnsupportedOperationException("TestFacade removed");
            } else {
                JOptionPane.showMessageDialog(getMainFrame(), "Wrong input format");
            }
        }
    });

    dev.put("webPrefs", new AbstractAction("Test Web Prefs-Access") {

        @Override
        public void actionPerformed(ActionEvent e) {
            String s = JOptionPane.showInputDialog(getMainFrame(), "Access-Path");
            if (s == null)
                return;
            try {
                Map<String, String> m = getWebAccessPrefs().getPrefsMap(s);
                StringBuilder sb = new StringBuilder();
                for (String k : m.keySet())
                    sb.append(k).append(": ").append(m.get(k)).append("\n");
                JOptionPane.showMessageDialog(getMainFrame(), sb.toString());
            } catch (CommonBusinessException e1) {
                Errors.getInstance().showExceptionDialog(getMainFrame(), e1);
            }
        }
    });

    dev.put("uiDefaults", new AbstractAction("UIDefaults") {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFrame out = new JFrame("UIDefaults");
            out.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            out.getContentPane().setLayout(new BorderLayout());
            final UIDefTableModel mdl = new UIDefTableModel();
            final JTable contentTable = new JTable(mdl);
            JScrollPane sp = new JScrollPane(contentTable);
            out.getContentPane().add(sp, BorderLayout.CENTER);

            UIDefaults defs = UIManager.getDefaults();
            for (Object key : CollectionUtils.iterableEnum((defs.keys())))
                mdl.add(key.toString(), defs.get(key));
            mdl.sort();

            contentTable.getColumnModel().getColumn(1).setCellRenderer(new UIDefaultsRenderer());
            contentTable.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    int row = contentTable.rowAtPoint(e.getPoint());
                    mdl.forceValue(contentTable.convertRowIndexToModel(row));
                }
            });
            out.pack();
            out.setVisible(true);
        }
    });

    dev.put("checkJawin", new AbstractAction("Check Jawin") {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                SystemUtils.checkJawin();
                JOptionPane.showMessageDialog(Main.getInstance().getMainFrame(), "Jawin ok");
            } catch (Exception ex) {
                Errors.getInstance().showDetailedExceptionDialog(Main.getInstance().getMainFrame(), ex);
            }
        }
    });

    res.put("Dev", dev);

    return res;
}

From source file:org.nuclos.client.ui.collect.component.AbstractCollectableComponent.java

public static void setBackgroundColor(Component cellRendererComponent, JTable tbl, Object oValue,
        boolean bSelected, boolean bHasFocus, int iRow, int iColumn) {
    cellRendererComponent.setBackground(bSelected ? tbl.getSelectionBackground()
            : iRow % 2 == 0 ? tbl.getBackground() : NuclosThemeSettings.BACKGROUND_PANEL);
    cellRendererComponent.setForeground(bSelected ? tbl.getSelectionForeground() : tbl.getForeground());

    final TableModel tm;
    final int adjustColIndex;
    if (tbl instanceof FixedColumnRowHeader.HeaderTable
            && ((FixedColumnRowHeader.HeaderTable) tbl).getExternalTable() != null) {
        tm = ((FixedColumnRowHeader.HeaderTable) tbl).getExternalTable().getModel();
        adjustColIndex = FixedRowIndicatorTableModel.ROWMARKERCOLUMN_COUNT;
    } else {//from   w w w  . j  a  v a2  s. co m
        tm = tbl.getModel();
        adjustColIndex = 0;
    }

    // check whether the data of the component is readable for current user, by asking the security agent of the actual field
    if (tm instanceof SortableCollectableTableModel<?>) {
        final SortableCollectableTableModel<Collectable> tblModel = (SortableCollectableTableModel<Collectable>) tm;
        if (tblModel.getRowCount() > iRow) {
            final Collectable clct = tblModel.getCollectable(iRow);
            final Integer iTColumn = tbl.getColumnModel().getColumn(iColumn).getModelIndex() - adjustColIndex;
            final CollectableEntityField clctef = tblModel.getCollectableEntityField(iTColumn);
            if (clctef == null) {
                throw new NullPointerException("getTableCellRendererComponent failed to find field: " + clct
                        + " tm index " + iTColumn);
            }

            boolean isEnabled = true;
            if (!clctef.isNullable() && isNull(oValue)) {
                cellRendererComponent.setBackground(getMandatoryColor());
                cellRendererComponent.setForeground(tbl.getForeground());
            } else {
                //               if (clct.getId() == null) {
                //                  cellRendererComponent.setBackground(tbl.getBackground());
                //                  cellRendererComponent.setForeground(tbl.getForeground());
                //               } else {
                if (tbl instanceof SubForm.SubFormTable) {
                    SubFormTable subformtable = (SubForm.SubFormTable) tbl;
                    Column subformcolumn = subformtable.getSubForm().getColumn(clctef.getName());
                    if (subformcolumn != null && !subformcolumn.isEnabled()) {
                        isEnabled = false;
                        if (bSelected) {
                            cellRendererComponent
                                    .setBackground(NuclosThemeSettings.BACKGROUND_INACTIVESELECTEDCOLUMN);
                        } else {
                            cellRendererComponent.setBackground(NuclosThemeSettings.BACKGROUND_INACTIVECOLUMN);
                        }
                    }
                }
                //               }

                try {
                    EntityMetaDataVO meta = MetaDataClientProvider.getInstance()
                            .getEntity(clctef.getEntityName());
                    if (meta.getRowColorScript() != null && !bSelected) {
                        AbstractCollectableComponent.setBackground(cellRendererComponent,
                                meta.getRowColorScript(), clct, meta, isEnabled);
                    }
                } catch (CommonFatalException ex) {
                    LOG.warn(ex);
                }
            }
        }
    }

    if (tbl instanceof TableRowMouseOverSupport) {
        TableRowMouseOverSupport trmos = (TableRowMouseOverSupport) tbl;
        if (trmos.isMouseOverRow(iRow)) {
            final Color bgColor = LangUtils.defaultIfNull(cellRendererComponent.getBackground(), Color.WHITE);
            cellRendererComponent
                    .setBackground(new Color(Math.max(0, bgColor.getRed() - (bgColor.getRed() * 8 / 100)),
                            Math.max(0, bgColor.getGreen() - (bgColor.getGreen() * 8 / 100)),
                            Math.max(0, bgColor.getBlue() - (bgColor.getBlue() * 8 / 100))));
            //            cellRendererComponent.setBackground(UIManager.getColor("Table.selectionBackground"));
        }
    }
}

From source file:org.nuclos.client.ui.collect.result.ResultController.java

/**
 * command: select columns/*from  w w w.  j  a va 2  s  .c  o  m*/
 * Lets the user select the columns to show in the result list.
 */
public void cmdSelectColumns(final ChoiceEntityFieldList fields) {
    final SelectColumnsController ctl = new SelectColumnsController(clctctl.getTab());
    // final List<CollectableEntityField> lstAvailable = (List<CollectableEntityField>) fields.getAvailableFields();
    // final List<CollectableEntityField> lstSelected = (List<CollectableEntityField>) fields.getSelectedFields();
    final ResultPanel<Clct> panel = getResultPanel();
    final JTable tbl = panel.getResultTable();

    final Map<String, Integer> mpWidths = panel.getVisibleColumnWidth(fields.getSelectedFields());
    ctl.setModel(fields);
    final boolean bOK = ctl.run(getSpringLocaleDelegate().getMessage("SelectColumnsController.1",
            "Anzuzeigende Spalten ausw\u00e4hlen"));

    if (bOK) {
        UIUtils.runCommand(clctctl.getTab(), new CommonRunnable() {
            @Override
            public void run() throws CommonBusinessException {
                final int iSelectedRow = tbl.getSelectedRow();
                fields.set(ctl.getAvailableObjects(), ctl.getSelectedObjects(),
                        clctctl.getResultController().getCollectableEntityFieldComparator());
                final List<? extends CollectableEntityField> lstSelectedNew = fields.getSelectedFields();
                ((CollectableTableModel<?>) tbl.getModel()).setColumns(lstSelectedNew);
                panel.setupTableCellRenderers(tbl);
                Collection<CollectableEntityField> collNewlySelected = new ArrayList<CollectableEntityField>(
                        lstSelectedNew);
                collNewlySelected.removeAll(fields.getSelectedFields());
                if (!collNewlySelected.isEmpty()) {
                    if (!clctctl.getSearchStrategy().getCollectablesInResultAreAlwaysComplete()) {
                        // refresh the result:
                        clctctl.getResultController().getSearchResultStrategy().refreshResult();
                    }
                }

                // reselect the previously selected row (which gets lost be refreshing the model)
                if (iSelectedRow != -1) {
                    tbl.setRowSelectionInterval(iSelectedRow, iSelectedRow);
                }

                isIgnorePreferencesUpdate = true;
                panel.restoreColumnWidths(ctl.getSelectedObjects(), mpWidths);
                isIgnorePreferencesUpdate = false;

                // Set the newly added columns to optimal width
                for (CollectableEntityField clctef : collNewlySelected) {
                    TableUtils.setOptimalColumnWidth(tbl,
                            tbl.getColumnModel().getColumnIndex(clctef.getLabel()));
                }
            }
        });
    }
}

From source file:org.o3project.optsdn.don.frame.NeFrame.java

/**
 * Create a pane that displays OMS connection information.
 * /*from  w  w w  .j a  v  a  2 s.c om*/
 * @return The pane that displays OMS connection information
 */
private JScrollPane createOmsConnectionInfoPane() {
    Object[] header = OMS_CONNECTION_INFO_COLNAME_LIST.toArray();

    String[][] rowDataList = new String[omsConnectionInfoList.size()][header.length];
    for (int i = 0; i < rowDataList.length; i++) {
        List<Port> omsConnectionInfo = omsConnectionInfoList.get(i);

        Port port = omsConnectionInfo.get(0);
        int ofPortIndex = OMS_CONNECTION_INFO_COLNAME_LIST.indexOf(OmsConnectionInfoCols.OF_PORT.getName());
        Integer openFlowPortId1 = port.getOpenFlowPortId();
        String ofPortValue1;
        if (openFlowPortId1 == null) {
            ofPortValue1 = OFPORT_NOTFOUND;
        } else {
            ofPortValue1 = String.valueOf(openFlowPortId1);
        }
        rowDataList[i][ofPortIndex] = ofPortValue1;

        Port port2 = omsConnectionInfo.get(1);
        int connectedToIndex = OMS_CONNECTION_INFO_COLNAME_LIST
                .indexOf(OmsConnectionInfoCols.CONNECTED_TO.getName());
        Integer openFlowPortId2 = port2.getOpenFlowPortId();
        String ofPortValue2;
        if (openFlowPortId2 == null) {
            ofPortValue2 = OFPORT_NOTFOUND;
        } else {
            ofPortValue2 = String.valueOf(openFlowPortId2);
        }
        rowDataList[i][connectedToIndex] = port2.getNeId() + ", " + ofPortValue2;
    }

    JTable connectedTable = new JTable(rowDataList, header);

    connectedTable.getTableHeader().setBackground(Color.WHITE);

    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    for (int i = 0; i < header.length; i++) {
        TableColumn column = connectedTable.getColumnModel().getColumn(i);
        column.setCellRenderer(renderer);
    }

    JScrollPane connectedPane = new JScrollPane();
    connectedPane.getViewport().setView(connectedTable);
    connectedPane.setPreferredSize(new Dimension(connectedPane.getPreferredSize().width, TABLE_HEIGHT));
    return connectedPane;
}