private static void drawSelection(JTable table, int column, Graphics g, final int width) { int y = 0; final int[] rows = table.getSelectedRows(); final int height = table.getRowHeight(); for (int row : rows) { final TableCellRenderer renderer = table.getCellRenderer(row, column); final Component component = renderer.getTableCellRendererComponent( table, table.getValueAt(row, column), false, false, row, column); g.translate(0, y); component.setBounds(0, 0, width, height); boolean wasOpaque = false; if (component instanceof JComponent) { final JComponent j = (JComponent) component; if (j.isOpaque()) wasOpaque = true; j.setOpaque(false); } component.paint(g); if (wasOpaque) { ((JComponent) component).setOpaque(true); } y += height; g.translate(0, -y); } }
private static Component setLabelColors( final Component label, final JTable table, final boolean isSelected, final int row) { if (label instanceof JComponent) { ((JComponent) label).setOpaque(true); } label.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); label.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); return label; }
private static int columnMaxWidth(@NotNull JTable table, int col) { TableColumn column = table.getColumnModel().getColumn(col); int width = 0; for (int row = 0; row < table.getRowCount(); row++) { Component component = table.prepareRenderer(column.getCellRenderer(), row, col); int rendererWidth = component.getPreferredSize().width; width = Math.max(width, rendererWidth + table.getIntercellSpacing().width); } return width; }
@Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (!table.isCellEditable(row, column)) { myBlankPanel.setBackground( isSelected ? table.getSelectionBackground() : table.getBackground()); return myBlankPanel; } return myDelegate.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); }
private static Rectangle fitToScreen( @NotNull Dimension newDim, @NotNull RelativePoint popupPosition, JTable table) { Rectangle rectangle = new Rectangle(popupPosition.getScreenPoint(), newDim); ScreenUtil.fitToScreen(rectangle); if (rectangle.getHeight() != newDim.getHeight()) { int newHeight = (int) rectangle.getHeight(); int roundedHeight = newHeight - newHeight % table.getRowHeight(); rectangle.setSize((int) rectangle.getWidth(), Math.max(roundedHeight, table.getRowHeight())); } return rectangle; }
private void setSizeAndDimensions( @NotNull JTable table, @NotNull JBPopup popup, @NotNull RelativePoint popupPosition, @NotNull List<UsageNode> data) { JComponent content = popup.getContent(); Window window = SwingUtilities.windowForComponent(content); Dimension d = window.getSize(); int width = calcMaxWidth(table); width = (int) Math.max(d.getWidth(), width); Dimension headerSize = ((AbstractPopup) popup).getHeaderPreferredSize(); width = Math.max((int) headerSize.getWidth(), width); width = Math.max(myWidth, width); if (myWidth == -1) myWidth = width; int newWidth = Math.max(width, d.width + width - myWidth); myWidth = newWidth; int rowsToShow = Math.min(30, data.size()); Dimension dimension = new Dimension(newWidth, table.getRowHeight() * rowsToShow); Rectangle rectangle = fitToScreen(dimension, popupPosition, table); dimension = rectangle.getSize(); Point location = window.getLocation(); if (!location.equals(rectangle.getLocation())) { window.setLocation(rectangle.getLocation()); } if (!data.isEmpty()) { TableScrollingUtil.ensureSelectionExists(table); } table.setSize(dimension); // table.setPreferredSize(dimension); // table.setMaximumSize(dimension); // table.setPreferredScrollableViewportSize(dimension); Dimension footerSize = ((AbstractPopup) popup).getFooterPreferredSize(); int newHeight = (int) (dimension.height + headerSize.getHeight() + footerSize.getHeight()) + 4 /* invisible borders, margins etc*/; Dimension newDim = new Dimension(dimension.width, newHeight); window.setSize(newDim); window.setMinimumSize(newDim); window.setMaximumSize(newDim); window.validate(); window.repaint(); table.revalidate(); table.repaint(); }
public static Image createImage(final JTable table, int column) { final int height = Math.max(20, Math.min(100, table.getSelectedRowCount() * table.getRowHeight())); final int width = table.getColumnModel().getColumn(column).getWidth(); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = (Graphics2D) image.getGraphics(); g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); drawSelection(table, column, g2, width); return image; }
@NotNull @Override public Component getTableCellRendererComponent( @NotNull JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final RegistryValue v = ((MyTableModel) table.getModel()).getRegistryValue(row); myLabel.setIcon(null); myLabel.setText(null); myLabel.setHorizontalAlignment(SwingConstants.LEFT); Color fg = isSelected ? table.getSelectionForeground() : table.getForeground(); Color bg = isSelected ? table.getSelectionBackground() : table.getBackground(); if (v != null) { switch (column) { case 0: myLabel.setIcon(v.isRestartRequired() ? RESTART_ICON : null); myLabel.setHorizontalAlignment(SwingConstants.CENTER); break; case 1: myLabel.setText(v.getKey()); break; case 2: if (v.asColor(null) != null) { myLabel.setIcon(createColoredIcon(v.asColor(null))); } else if (v.isBoolean()) { final JCheckBox box = new JCheckBox(); box.setSelected(v.asBoolean()); box.setBackground(bg); return box; } else { myLabel.setText(v.asString()); } } myLabel.setOpaque(true); myLabel.setFont( myLabel.getFont().deriveFont(v.isChangedFromDefault() ? Font.BOLD : Font.PLAIN)); myLabel.setForeground(fg); myLabel.setBackground(bg); } return myLabel; }
private void rebuildPopup( @NotNull final UsageViewImpl usageView, @NotNull final List<Usage> usages, @NotNull List<UsageNode> nodes, @NotNull final JTable table, @NotNull final JBPopup popup, @NotNull final UsageViewPresentation presentation, @NotNull final RelativePoint popupPosition, boolean findUsagesInProgress) { ApplicationManager.getApplication().assertIsDispatchThread(); boolean shouldShowMoreSeparator = usages.contains(MORE_USAGES_SEPARATOR); if (shouldShowMoreSeparator) { nodes.add(MORE_USAGES_SEPARATOR_NODE); } String title = presentation.getTabText(); String fullTitle = getFullTitle( usages, title, shouldShowMoreSeparator, nodes.size() - (shouldShowMoreSeparator ? 1 : 0), findUsagesInProgress); ((AbstractPopup) popup).setCaption(fullTitle); List<UsageNode> data = collectData(usages, nodes, usageView, presentation); MyModel tableModel = setTableModel(table, usageView, data); List<UsageNode> existingData = tableModel.getItems(); int row = table.getSelectedRow(); int newSelection = updateModel(tableModel, existingData, data, row == -1 ? 0 : row); if (newSelection < 0 || newSelection >= tableModel.getRowCount()) { TableScrollingUtil.ensureSelectionExists(table); newSelection = table.getSelectedRow(); } else { table.getSelectionModel().setSelectionInterval(newSelection, newSelection); } TableScrollingUtil.ensureIndexIsVisible(table, newSelection, 0); setSizeAndDimensions(table, popup, popupPosition, data); }
private static int calcMaxWidth(JTable table) { int colsNum = table.getColumnModel().getColumnCount(); int totalWidth = 0; for (int col = 0; col < colsNum - 1; col++) { TableColumn column = table.getColumnModel().getColumn(col); int preferred = column.getPreferredWidth(); int width = Math.max(preferred, columnMaxWidth(table, col)); totalWidth += width; column.setMinWidth(width); column.setMaxWidth(width); column.setWidth(width); column.setPreferredWidth(width); } totalWidth += columnMaxWidth(table, colsNum - 1); return totalWidth; }
@NotNull private static MyModel setTableModel( @NotNull JTable table, @NotNull UsageViewImpl usageView, @NotNull final List<UsageNode> data) { ApplicationManager.getApplication().assertIsDispatchThread(); final int columnCount = calcColumnCount(data); MyModel model = table.getModel() instanceof MyModel ? (MyModel) table.getModel() : null; if (model == null || model.getColumnCount() != columnCount) { model = new MyModel(data, columnCount); table.setModel(model); ShowUsagesTableCellRenderer renderer = new ShowUsagesTableCellRenderer(usageView); for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) { TableColumn column = table.getColumnModel().getColumn(i); column.setCellRenderer(renderer); } } return model; }
@Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component rendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); Object commit = getValueAt(row, AbstractVcsLogTableModel.COMMIT_COLUMN); if (commit instanceof GraphCommitCell) { setBackground(isSelected ? table.getSelectionBackground() : JBColor.WHITE); } return rendererComponent; }
private String extractContent( DataGridPanel grid, String delimiter, boolean saveHeader, boolean ecloseWithDowbleQuotes) { JTable _table = grid.getTable(); int numcols = _table.getSelectedColumnCount(); int numrows = _table.getSelectedRowCount(); if (numcols > 0 && numrows > 0) { StringBuffer sbf = new StringBuffer(); int[] rowsselected = _table.getSelectedRows(); int[] colsselected = _table.getSelectedColumns(); if (saveHeader) { // put header name list for (int j = 0; j < numcols; j++) { String text = (String) _table .getTableHeader() .getColumnModel() .getColumn(colsselected[j]) .getHeaderValue(); sbf.append(text); if (j < numcols - 1) sbf.append(delimiter); } sbf.append("\n"); } // put content for (int i = 0; i < numrows; i++) { for (int j = 0; j < numcols; j++) { Object value = _table.getValueAt(rowsselected[i], colsselected[j]); String _value = ""; if (value != null) { _value = value.toString(); } if (ecloseWithDowbleQuotes) { sbf.append("\"").append(_value).append("\""); } else { sbf.append(_value); } if (j < numcols - 1) sbf.append(delimiter); } sbf.append("\n"); } // StringSelection stsel = new StringSelection(sbf.toString()); // Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard(); // system.setContents(stsel, stsel); return sbf.toString(); } return null; }
@Override public void update(AnActionEvent e) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); e.getPresentation().setEnabled(false); if (focusOwner instanceof JComponent && SpeedSearchBase.hasActiveSpeedSearch((JComponent) focusOwner)) { return; } if (StackingPopupDispatcher.getInstance().isPopupFocused()) return; if (focusOwner instanceof JTree) { JTree tree = (JTree) focusOwner; if (!tree.isEditing()) { e.getPresentation().setEnabled(true); } } else if (focusOwner instanceof JTable) { JTable table = (JTable) focusOwner; if (!table.isEditing()) { e.getPresentation().setEnabled(true); } } }
@Nullable public Component getTableCellEditorComponent( JTable table, Object value, boolean isSelected, int row, int column) { myValue = ((MyTableModel) table.getModel()).getRegistryValue(row); if (myValue.asColor(null) != null) { final Color color = ColorChooser.chooseColor( table, "Choose color", ((RegistryValue) value).asColor(Color.WHITE)); if (color != null) { myValue.setValue(color.getRed() + "," + color.getGreen() + "," + color.getBlue()); } return null; } else if (myValue.isBoolean()) { myCheckBox.setSelected(myValue.asBoolean()); myCheckBox.setBackground(table.getBackground()); return myCheckBox; } else { myField.setText(myValue.asString()); myField.setBorder(null); myField.selectAll(); return myField; } }
@Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { String text; Color color; if (value instanceof VirtualFile) { VirtualFile root = (VirtualFile) value; int readableRow = ScrollingUtil.getReadableRow(table, Math.round(myUi.getTable().getRowHeight() * 0.5f)); if (row < readableRow) { text = ""; } else if (row == 0 || !value.equals(table.getModel().getValueAt(row - 1, column)) || readableRow == row) { text = root.getName(); } else { text = ""; } color = getRootBackgroundColor(root, myUi.getColorManager()); } else { text = null; color = UIUtil.getTableBackground(isSelected); } myColor = color; Color background = ((VcsLogGraphTable) table) .getStyle(row, column, text, hasFocus, isSelected) .getBackground(); assert background != null; myBorderColor = background; setForeground(UIUtil.getTableForeground(false)); if (myUi.isShowRootNames()) { setText(text); isNarrow = false; } else { setText(""); isNarrow = true; } return this; }
@NotNull private JBPopup createUsagePopup( @NotNull final List<Usage> usages, @NotNull final UsageInfoToUsageConverter.TargetElementsDescriptor descriptor, @NotNull Set<UsageNode> visibleNodes, @NotNull final FindUsagesHandler handler, final Editor editor, @NotNull final RelativePoint popupPosition, final int maxUsages, @NotNull final UsageViewImpl usageView, @NotNull final FindUsagesOptions options, @NotNull final JTable table, @NotNull final UsageViewPresentation presentation, @NotNull final AsyncProcessIcon processIcon, boolean hadMoreSeparator) { table.setRowHeight(PlatformIcons.CLASS_ICON.getIconHeight() + 2); table.setShowGrid(false); table.setShowVerticalLines(false); table.setShowHorizontalLines(false); table.setTableHeader(null); table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); table.setIntercellSpacing(new Dimension(0, 0)); PopupChooserBuilder builder = new PopupChooserBuilder(table); final String title = presentation.getTabText(); if (title != null) { String result = getFullTitle(usages, title, hadMoreSeparator, visibleNodes.size() - 1, true); builder.setTitle(result); builder.setAdText(getSecondInvocationTitle(options, handler)); } builder.setMovable(true).setResizable(true); builder.setItemChoosenCallback( new Runnable() { @Override public void run() { int[] selected = table.getSelectedRows(); for (int i : selected) { Object value = table.getValueAt(i, 0); if (value instanceof UsageNode) { Usage usage = ((UsageNode) value).getUsage(); if (usage == MORE_USAGES_SEPARATOR) { appendMoreUsages(editor, popupPosition, handler, maxUsages); return; } navigateAndHint(usage, null, handler, popupPosition, maxUsages, options); } } } }); final JBPopup[] popup = new JBPopup[1]; KeyboardShortcut shortcut = UsageViewImpl.getShowUsagesWithSettingsShortcut(); if (shortcut != null) { new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { popup[0].cancel(); showDialogAndFindUsages(handler, popupPosition, editor, maxUsages); } }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table); } shortcut = getShowUsagesShortcut(); if (shortcut != null) { new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { popup[0].cancel(); searchEverywhere(options, handler, editor, popupPosition, maxUsages); } }.registerCustomShortcutSet(new CustomShortcutSet(shortcut.getFirstKeyStroke()), table); } InplaceButton settingsButton = createSettingsButton( handler, popupPosition, editor, maxUsages, new Runnable() { @Override public void run() { popup[0].cancel(); } }); ActiveComponent spinningProgress = new ActiveComponent() { @Override public void setActive(boolean active) {} @Override public JComponent getComponent() { return processIcon; } }; builder.setCommandButton(new CompositeActiveComponent(spinningProgress, settingsButton)); DefaultActionGroup toolbar = new DefaultActionGroup(); usageView.addFilteringActions(toolbar); toolbar.add(UsageGroupingRuleProviderImpl.createGroupByFileStructureAction(usageView)); toolbar.add( new AnAction( "Open Find Usages Toolwindow", "Show all usages in a separate toolwindow", AllIcons.Toolwindows.ToolWindowFind) { { AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_FIND_USAGES); setShortcutSet(action.getShortcutSet()); } @Override public void actionPerformed(AnActionEvent e) { hideHints(); popup[0].cancel(); FindUsagesManager findUsagesManager = ((FindManagerImpl) FindManager.getInstance(usageView.getProject())) .getFindUsagesManager(); findUsagesManager.findUsages( handler.getPrimaryElements(), handler.getSecondaryElements(), handler, options, FindSettings.getInstance().isSkipResultsWithOneUsage()); } }); ActionToolbar actionToolbar = ActionManager.getInstance() .createActionToolbar(ActionPlaces.USAGE_VIEW_TOOLBAR, toolbar, true); actionToolbar.setReservePlaceAutoPopupIcon(false); final JComponent toolBar = actionToolbar.getComponent(); toolBar.setOpaque(false); builder.setSettingButton(toolBar); popup[0] = builder.createPopup(); JComponent content = popup[0].getContent(); myWidth = (int) (toolBar.getPreferredSize().getWidth() + new JLabel( getFullTitle( usages, title, hadMoreSeparator, visibleNodes.size() - 1, true)) .getPreferredSize() .getWidth() + settingsButton.getPreferredSize().getWidth()); myWidth = -1; for (AnAction action : toolbar.getChildren(null)) { action.unregisterCustomShortcutSet(usageView.getComponent()); action.registerCustomShortcutSet(action.getShortcutSet(), content); } return popup[0]; }
@NotNull @Override public RelativePoint guessBestPopupLocation(@NotNull final JComponent component) { Point popupMenuPoint = null; final Rectangle visibleRect = component.getVisibleRect(); if (component instanceof JList) { // JList JList list = (JList) component; int firstVisibleIndex = list.getFirstVisibleIndex(); int lastVisibleIndex = list.getLastVisibleIndex(); int[] selectedIndices = list.getSelectedIndices(); for (int index : selectedIndices) { if (firstVisibleIndex <= index && index <= lastVisibleIndex) { Rectangle cellBounds = list.getCellBounds(index, index); popupMenuPoint = new Point(visibleRect.x + visibleRect.width / 4, cellBounds.y + cellBounds.height); break; } } } else if (component instanceof JTree) { // JTree JTree tree = (JTree) component; int[] selectionRows = tree.getSelectionRows(); if (selectionRows != null) { Arrays.sort(selectionRows); for (int i = 0; i < selectionRows.length; i++) { int row = selectionRows[i]; Rectangle rowBounds = tree.getRowBounds(row); if (visibleRect.contains(rowBounds)) { popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1); break; } } if (popupMenuPoint == null) { // All selected rows are out of visible rect Point visibleCenter = new Point( visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2); double minDistance = Double.POSITIVE_INFINITY; int bestRow = -1; Point rowCenter; double distance; for (int i = 0; i < selectionRows.length; i++) { int row = selectionRows[i]; Rectangle rowBounds = tree.getRowBounds(row); rowCenter = new Point(rowBounds.x + rowBounds.width / 2, rowBounds.y + rowBounds.height / 2); distance = visibleCenter.distance(rowCenter); if (minDistance > distance) { minDistance = distance; bestRow = row; } } if (bestRow != -1) { Rectangle rowBounds = tree.getRowBounds(bestRow); tree.scrollRectToVisible( new Rectangle( rowBounds.x, rowBounds.y, Math.min(visibleRect.width, rowBounds.width), rowBounds.height)); popupMenuPoint = new Point(rowBounds.x + 2, rowBounds.y + rowBounds.height - 1); } } } } else if (component instanceof JTable) { JTable table = (JTable) component; int column = table.getColumnModel().getSelectionModel().getLeadSelectionIndex(); int row = Math.max( table.getSelectionModel().getLeadSelectionIndex(), table.getSelectionModel().getAnchorSelectionIndex()); Rectangle rect = table.getCellRect(row, column, false); if (!visibleRect.intersects(rect)) { table.scrollRectToVisible(rect); } popupMenuPoint = new Point(rect.x, rect.y + rect.height); } else if (component instanceof PopupOwner) { popupMenuPoint = ((PopupOwner) component).getBestPopupPosition(); } if (popupMenuPoint == null) { popupMenuPoint = new Point(visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2); } return new RelativePoint(component, popupMenuPoint); }
public void setSelected(AnActionEvent event, boolean b) { switch (command) { case REFRESH_RESULTSET: { QueryResultPanel resultPanel = getSelectedResultPanel(); if (isConnected && resultPanel instanceof DataGridPanel && resultPanel.isRefreshSupported()) { try { resultPanel.refresh(); } catch (DBException e) { } } break; } case CLOSE_PANEL: close(); break; case STICKY_OPTION: selected ^= true; break; case EXPORT_DATA: { QueryResultPanel resultPanel = getSelectedResultPanel(); if (resultPanel instanceof DataGridPanel) { DataGridPanel grid = (DataGridPanel) resultPanel; JTable _table = grid.getTable(); int numcols = _table.getSelectedColumnCount(); int numrows = _table.getSelectedRowCount(); if (numcols == 0 && numrows == 0) { // nothing to copy return; } ExportSettings settings = new ExportSettings(); settings.show(); if (!settings.isOK()) { return; } File fileToSave = null; if (settings.saveToFile()) { String path = settings.getFilePathToSave(); if (path == null || path.length() == 0) { Messages.showInfoMessage( "File not specified, content will be saved in Clipboard", "File not specified"); // } else if (new File(path).getParentFile().exists()) // { } else { // todo -- fileToSave = new File(path); } } String delimiter; switch (settings.getDelimiter()) { case TAB: delimiter = "\t"; break; case COMMA: delimiter = ","; break; default: // SEMICOLON: delimiter = ";"; break; } String content = extractContent( grid, delimiter, settings.saveColumnHeaders(), settings.encloseFieldsInDowubleQuotes()); if (content != null) { if (fileToSave != null) { // save in the file try { StringUtils.string2file(content, fileToSave); } catch (IOException e) { Messages.showErrorDialog(e.getMessage(), "Export failed"); } } else { // save in Clipboard StringSelection stsel = new StringSelection(content); Clipboard system = Toolkit.getDefaultToolkit().getSystemClipboard(); system.setContents(stsel, stsel); } } } break; } } // notifyListeners(command); }