Example usage for com.intellij.openapi.ui.popup JBPopup showCenteredInCurrentWindow

List of usage examples for com.intellij.openapi.ui.popup JBPopup showCenteredInCurrentWindow

Introduction

In this page you can find the example usage for com.intellij.openapi.ui.popup JBPopup showCenteredInCurrentWindow.

Prototype

void showCenteredInCurrentWindow(@NotNull Project project);

Source Link

Document

Shows the popup in the center of the active window in the IDE frame for the specified project.

Usage

From source file:com.android.tools.idea.lint.ShowCustomIssueExplanationFix.java

License:Apache License

@Override
public void apply(@NotNull PsiElement startElement, @NotNull PsiElement endElement,
        @NotNull AndroidQuickfixContexts.Context context) {
    Project project = myElement.getProject();
    DocumentationManager manager = DocumentationManager.getInstance(project);
    DocumentationComponent component = new DocumentationComponent(manager);
    component.setText("<html>" + myIssue.getExplanation(TextFormat.HTML) + "</html>", myElement, false);
    JBPopup popup = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component)
            .setDimensionServiceKey(project, DocumentationManager.JAVADOC_LOCATION_AND_SIZE, false)
            .setResizable(true).setMovable(true).setRequestFocus(true).createPopup();
    component.setHint(popup);//from  ww  w  . ja  v a  2s.co  m
    if (context.getType() == AndroidQuickfixContexts.EditorContext.TYPE) {
        popup.showInBestPositionFor(((AndroidQuickfixContexts.EditorContext) context).getEditor());
    } else {
        popup.showCenteredInCurrentWindow(project);
    }
    Disposer.dispose(component);
}

From source file:com.favorite.FavoriteBaseShowRecentFilesAction.java

License:Apache License

protected void show(final Project project) {
    final DefaultListModel model = new DefaultListModel();

    FileEditorManagerEx fem = FileEditorManagerEx.getInstanceEx(project);
    VirtualFile[] selectedFiles = fem.getSelectedFiles();
    VirtualFile currentFile = fem.getCurrentFile();
    VirtualFile[] files = filesToShow(project);
    FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance();

    for (int i = files.length - 1; i >= 0; i--) { // reverse order of files
        VirtualFile file = files[i];/*w  ww.  j  a va 2 s.c o  m*/
        boolean isSelected = ArrayUtil.find(selectedFiles, file) >= 0;
        boolean equals = file.equals(currentFile);
        FileEditorProvider[] providers = editorProviderManager.getProviders(project, file);
        boolean length = true;//providers.length > 0;
        if ((!isSelected || !equals) && length) {
            // 1. do not put currently selected file
            // 2. do not include file with no corresponding editor providers
            model.addElement(file);
        }
    }

    final JLabel pathLabel = new JLabel(" ");
    pathLabel.setHorizontalAlignment(SwingConstants.RIGHT);

    if (true /*SystemInfo.isMac*/) {
        final Font font = pathLabel.getFont();
        pathLabel.setFont(font.deriveFont((float) 10));
    }

    final JList list = new JBList(model);
    list.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                int index = list.getSelectedIndex();
                if (index == -1 || index >= list.getModel().getSize()) {
                    return;
                }
                Object[] values = list.getSelectedValues();
                for (Object value : values) {
                    VirtualFile file = (VirtualFile) value;
                    model.removeElement(file);
                    if (model.getSize() > 0) {
                        if (model.getSize() == index) {
                            list.setSelectedIndex(model.getSize() - 1);
                        } else if (model.getSize() > index) {
                            list.setSelectedIndex(index);
                        }
                    } else {
                        list.clearSelection();
                    }
                    EditorHistoryManager.getInstance(project).removeFile(file);
                }
            }
        }
    });

    final MyListSelectionListener listSelectionListener = new MyListSelectionListener(pathLabel, list);
    list.getSelectionModel().addListSelectionListener(listSelectionListener);

    Runnable runnable = new Runnable() {
        public void run() {
            Object[] values = list.getSelectedValues();
            for (Object value : values) {
                VirtualFile file = (VirtualFile) value;
                if (file.isDirectory()) {
                    String path = file.getPath();
                    ProjectUtil.openOrImport(path, project, false);
                } else {
                    FileEditorManager.getInstance(project).openFile(file, true, true);
                }
                //String path = "/Volumes/SHARE/MacSystem/Home/Users/djzhang/NetBeansProjects/intellijPlugDemo";
                //String path = file.getPath();
                //final Project project = PlatformDataKeys.PROJECT.getData(e.getDataContext());

                //FileEditorManager.getInstance(project).openFile(file, true, true);

                //OpenFileAction.openFile(file, project);

            }
        }
    };

    if (list.getModel().getSize() == 0) {
        list.clearSelection();
    }

    list.setCellRenderer(new RecentFilesRenderer(project));

    /*
    TODO:
    if (model.getSize() > 0) {
      Dimension listPreferredSize = list.getPreferredSize();
      list.setVisibleRowCount(0);
      Dimension viewPreferredSize = new Dimension(listPreferredSize.width, Math.min(listPreferredSize.height, r.height - 20));
      ((JViewport)list.getParent()).setPreferredSize(viewPreferredSize);
    }
    */

    JPanel footerPanel = new JPanel(new BorderLayout()) {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(BORDER_COLOR);
            g.drawLine(0, 0, getWidth(), 0);
        }
    };

    footerPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    footerPanel.add(pathLabel);

    final PopupChooserBuilder builder = new PopupChooserBuilder(list).setTitle(getTitle()).setAdText(" ")
            .setMovable(true).setItemChoosenCallback(runnable).setModalContext(false)
            .addAdditionalChooseKeystroke(getAdditionalSelectKeystroke())
            .setFilteringEnabled(new Function<Object, String>() {
                public String fun(Object o) {
                    return o instanceof VirtualFile ? ((VirtualFile) o).getName() : "";
                }
            });
    final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(getPeerActionId());
    final PeerListener listener = new PeerListener(project, getPeerActionId());
    for (Shortcut shortcut : shortcuts) {
        if (shortcut instanceof KeyboardShortcut
                && ((KeyboardShortcut) shortcut).getSecondKeyStroke() == null) {
            final KeyStroke keyStroke = ((KeyboardShortcut) shortcut).getFirstKeyStroke();
            builder.registerKeyboardAction(keyStroke, listener);
        }
    }
    JBPopup popup = builder.createPopup();
    listener.setPopup(popup);
    listSelectionListener.setPopup(popup);
    popup.showCenteredInCurrentWindow(project);
}

From source file:com.intellij.codeInsight.daemon.impl.quickfix.AddModuleDependencyFix.java

License:Apache License

@Override
public void invoke(@NotNull final Project project, @Nullable final Editor editor, PsiFile file) {
    if (myModules.size() == 1) {
        addDependencyOnModule(project, editor, myModules.get(0));
    } else {//from  ww  w.  j ava2  s  .com
        final JBList list = new JBList(myModules);
        list.setCellRenderer(new ListCellRendererWrapper<Module>() {
            @Override
            public void customize(JList list, Module module, int index, boolean selected, boolean hasFocus) {
                if (module != null) {
                    setIcon(AllIcons.Nodes.Module);
                    setText(module.getName());
                }
            }
        });
        final JBPopup popup = JBPopupFactory.getInstance().createListPopupBuilder(list)
                .setTitle("Choose Module to Add Dependency on").setMovable(false).setResizable(false)
                .setRequestFocus(true).setItemChoosenCallback(new Runnable() {
                    @Override
                    public void run() {
                        final Object value = list.getSelectedValue();
                        if (value instanceof Module) {
                            addDependencyOnModule(project, editor, (Module) value);
                        }
                    }
                }).createPopup();
        if (editor != null) {
            popup.showInBestPositionFor(editor);
        } else {
            popup.showCenteredInCurrentWindow(project);
        }
    }
}

From source file:com.intellij.execution.actions.StopAction.java

License:Apache License

@Override
public void actionPerformed(final AnActionEvent e) {
    final DataContext dataContext = e.getDataContext();
    ProcessHandler activeProcessHandler = getHandler(dataContext);

    List<Pair<TaskInfo, ProgressIndicator>> backgroundTasks = getCancellableProcesses(e.getProject());
    if (ActionPlaces.MAIN_MENU.equals(e.getPlace())) {
        if (activeProcessHandler != null && !activeProcessHandler.isProcessTerminating()
                && !activeProcessHandler.isProcessTerminated() && backgroundTasks.isEmpty()) {
            stopProcess(activeProcessHandler);
            return;
        }//from   ww w .  j  a v  a  2 s  .c  o  m

        Pair<List<HandlerItem>, HandlerItem> handlerItems = getItemsList(backgroundTasks,
                getActiveDescriptors(dataContext), activeProcessHandler);
        if (handlerItems.first.isEmpty())
            return;

        final JBList list = new JBList(handlerItems.first);
        if (handlerItems.second != null)
            list.setSelectedValue(handlerItems.second, true);

        list.setCellRenderer(new GroupedItemsListRenderer(new ListItemDescriptor() {
            @Nullable
            @Override
            public String getTextFor(Object value) {
                return value instanceof HandlerItem ? ((HandlerItem) value).displayName : null;
            }

            @Nullable
            @Override
            public String getTooltipFor(Object value) {
                return null;
            }

            @Nullable
            @Override
            public Icon getIconFor(Object value) {
                return value instanceof HandlerItem ? ((HandlerItem) value).icon : null;
            }

            @Override
            public boolean hasSeparatorAboveOf(Object value) {
                return value instanceof HandlerItem && ((HandlerItem) value).hasSeparator;
            }

            @Nullable
            @Override
            public String getCaptionAboveOf(Object value) {
                return null;
            }
        }));

        final PopupChooserBuilder builder = JBPopupFactory.getInstance().createListPopupBuilder(list);
        final JBPopup popup = builder.setMovable(true)
                .setTitle(handlerItems.first.size() == 1 ? "Confirm process stop" : "Stop process")
                .setFilteringEnabled(new Function<Object, String>() {
                    @Override
                    public String fun(Object o) {
                        return ((HandlerItem) o).displayName;
                    }
                }).setItemChoosenCallback(new Runnable() {
                    @Override
                    public void run() {
                        HandlerItem item = (HandlerItem) list.getSelectedValue();
                        if (item != null)
                            item.stop();
                    }
                }).setRequestFocus(true).createPopup();

        popup.showCenteredInCurrentWindow(e.getProject());
    } else {
        if (activeProcessHandler != null) {
            stopProcess(activeProcessHandler);
        }
    }
}

From source file:com.intellij.ide.actions.BaseShowRecentFilesAction.java

License:Apache License

protected void show(final Project project) {
    final DefaultListModel model = new DefaultListModel();

    FileEditorManagerEx fem = FileEditorManagerEx.getInstanceEx(project);
    VirtualFile[] selectedFiles = fem.getSelectedFiles();
    VirtualFile currentFile = fem.getCurrentFile();
    VirtualFile[] files = filesToShow(project);
    FileEditorProviderManager editorProviderManager = FileEditorProviderManager.getInstance();

    for (int i = files.length - 1; i >= 0; i--) { // reverse order of files
        VirtualFile file = files[i];/*from   w ww  . ja  v a2s. c  o  m*/
        boolean isSelected = ArrayUtil.find(selectedFiles, file) >= 0;
        if ((!isSelected || !file.equals(currentFile))
                && editorProviderManager.getProviders(project, file).length > 0) {
            // 1. do not put currently selected file
            // 2. do not include file with no corresponding editor providers
            model.addElement(file);
        }
    }

    final JLabel pathLabel = new JLabel(" ");
    pathLabel.setHorizontalAlignment(SwingConstants.RIGHT);

    if (true /*SystemInfo.isMac*/) {
        final Font font = pathLabel.getFont();
        pathLabel.setFont(font.deriveFont((float) 10));
    }

    final JList list = new JBList(model);
    list.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                int index = list.getSelectedIndex();
                if (index == -1 || index >= list.getModel().getSize()) {
                    return;
                }
                Object[] values = list.getSelectedValues();
                for (Object value : values) {
                    VirtualFile file = (VirtualFile) value;
                    model.removeElement(file);
                    if (model.getSize() > 0) {
                        if (model.getSize() == index) {
                            list.setSelectedIndex(model.getSize() - 1);
                        } else if (model.getSize() > index) {
                            list.setSelectedIndex(index);
                        }
                    } else {
                        list.clearSelection();
                    }
                    EditorHistoryManager.getInstance(project).removeFile(file);
                }
            }
        }
    });

    final MyListSelectionListener listSelectionListener = new MyListSelectionListener(pathLabel, list);
    list.getSelectionModel().addListSelectionListener(listSelectionListener);

    Runnable runnable = new Runnable() {
        public void run() {
            Object[] values = list.getSelectedValues();
            for (Object value : values) {
                VirtualFile file = (VirtualFile) value;
                FileEditorManager.getInstance(project).openFile(file, true, true);
            }
        }
    };

    if (list.getModel().getSize() == 0) {
        list.clearSelection();
    }

    list.setCellRenderer(new RecentFilesRenderer(project));

    /*
    TODO:
    if (model.getSize() > 0) {
      Dimension listPreferredSize = list.getPreferredSize();
      list.setVisibleRowCount(0);
      Dimension viewPreferredSize = new Dimension(listPreferredSize.width, Math.min(listPreferredSize.height, r.height - 20));
      ((JViewport)list.getParent()).setPreferredSize(viewPreferredSize);
    }
    */

    JPanel footerPanel = new JPanel(new BorderLayout()) {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(BORDER_COLOR);
            g.drawLine(0, 0, getWidth(), 0);
        }
    };

    footerPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    footerPanel.add(pathLabel);

    final PopupChooserBuilder builder = new PopupChooserBuilder(list).setTitle(getTitle()).setAdText(" ")
            .setMovable(true).setItemChoosenCallback(runnable).setModalContext(false)
            .addAdditionalChooseKeystroke(getAdditionalSelectKeystroke())
            .setFilteringEnabled(new Function<Object, String>() {
                public String fun(Object o) {
                    return o instanceof VirtualFile ? ((VirtualFile) o).getName() : "";
                }
            });
    final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(getPeerActionId());
    final PeerListener listener = new PeerListener(project, getPeerActionId());
    for (Shortcut shortcut : shortcuts) {
        if (shortcut instanceof KeyboardShortcut
                && ((KeyboardShortcut) shortcut).getSecondKeyStroke() == null) {
            final KeyStroke keyStroke = ((KeyboardShortcut) shortcut).getFirstKeyStroke();
            builder.registerKeyboardAction(keyStroke, listener);
        }
    }
    JBPopup popup = builder.createPopup();
    listener.setPopup(popup);
    listSelectionListener.setPopup(popup);
    popup.showCenteredInCurrentWindow(project);
}

From source file:com.kstenschke.referencer.actions.GoAction.java

License:Apache License

/**
 * Show list of bookmarks in current document to go to
 *
 * @param   e   Action system event/*  ww w  .  jav  a  2 s  .  c o  m*/
 */
public void actionPerformed(AnActionEvent e) {
    this.project = e.getData(PlatformDataKeys.PROJECT);
    this.editor = e.getData(PlatformDataKeys.EDITOR);

    if (this.project != null && this.editor != null) {
        this.document = this.editor.getDocument();
        this.file = FileDocumentManager.getInstance().getFile(document);
        final String fileExtension = (this.file != null) ? this.file.getExtension() : "";

        final Object[] refArr = this.getItems();
        if (refArr != null && refArr.length > 0) {
            final JBList referencesList = new JBList(refArr);
            referencesList.setCellRenderer(new DividedListCellRenderer());
            referencesList.addListSelectionListener(new DividedListSelectionListener());

            // Preselect item from preferences
            Integer selectedIndex = Preferences.getSelectedIndex(fileExtension);
            if (selectedIndex > refArr.length)
                selectedIndex = 0;

            referencesList.setSelectedIndex(selectedIndex);

            // Build and show popup
            PopupChooserBuilder popup = JBPopupFactory.getInstance().createListPopupBuilder(referencesList);

            JBPopup popupGo = popup.setTitle(StaticTexts.POPUP_TITLE_ACTION_GO)
                    .setItemChoosenCallback(new Runnable() {
                        public void run() {
                            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                                public void run() {
                                    // Callback when item chosen
                                    CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                                        public void run() {
                                            Preferences.saveSelectedIndex(fileExtension,
                                                    referencesList.getSelectedIndex());

                                            Integer lineNumber = Integer.parseInt(
                                                    referencesList.getSelectedValue().toString().split(":")[0]);
                                            editor.getCaretModel().moveToOffset(
                                                    document.getLineStartOffset(lineNumber), true);
                                            editor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
                                        }
                                    }, null, null);
                                }
                            });

                        }
                    }).setMovable(true).createPopup();

            // Add context menu
            PopupContextGo contextMenu = new PopupContextGo(popupGo, this.project);
            referencesList.addMouseListener(contextMenu.getPopupListener());

            popupGo.showCenteredInCurrentWindow(project);
        } else {
            UtilsEnvironment.notify(StaticTexts.NOTIFY_BOOKMARK_NONE_FOUND);
        }
    }
}

From source file:com.kstenschke.referencer.actions.GoToAction.java

License:Apache License

/**
 * Show list of bookmarks in current document to go to
 *
 * @param   e   Action system event/*from   www  .  java  2 s  .c  o m*/
 */
public void actionPerformed(AnActionEvent e) {
    this.project = e.getData(PlatformDataKeys.PROJECT);
    this.editor = e.getData(PlatformDataKeys.EDITOR);

    if (this.project != null && this.editor != null) {
        this.document = this.editor.getDocument();
        VirtualFile file = FileDocumentManager.getInstance().getFile(document);
        String fileExtension = UtilsFile.getExtensionByDocument(this.document);

        // Get bookmarks
        Object[] refArr = GoToReferencerBookmarks.getItems(this.project, this.document, file);
        // Add JS or PHP methods
        String[] methodItems = GoToReferencerMethods.getItems(this.document, fileExtension);
        if (methodItems != null && methodItems.length > 1) {
            refArr = ArrayUtils.addAll(refArr, methodItems);
        }
        // Add dynamical jump destination patterns
        if (GoToReferencerPatterns.hasPatternDefinitions()) {
            String[] patternDefinitions = GoToReferencerPatterns.getPatternDefinitions();
            for (String curPatterDefinition : patternDefinitions) {
                String[] curPatternItems = GoToReferencerPatterns.getItems(this.document, curPatterDefinition);
                if (curPatternItems != null && curPatternItems.length > 1) {
                    refArr = ArrayUtils.addAll(refArr, curPatternItems);
                }
            }
        }

        if (refArr != null && refArr.length > 0) {
            final JBList referencesList = new JBList(refArr);
            referencesList.setCellRenderer(new DividedListCellRenderer(referencesList));
            referencesList.addListSelectionListener(new DividedListSelectionListener());

            // Preselect item from preferences
            Integer selectedIndex = Preferences.getSelectedIndex(fileExtension);
            if (selectedIndex > refArr.length)
                selectedIndex = 0;

            referencesList.setSelectedIndex(selectedIndex);

            // Build and show popup
            JBPopup popupGo = buildPopup(fileExtension, referencesList);

            // Add context menu
            PopupContextGo contextMenu = new PopupContextGo(popupGo, this.project);
            referencesList.addMouseListener(contextMenu.getPopupListener());

            popupGo.showCenteredInCurrentWindow(project);
        }

        if ((refArr == null || refArr.length == 0)) {
            UtilsEnvironment.notify(StaticTexts.NOTIFY_GOTO_NONE_FOUND);
        }
    }
}