IDEA插件开发-第二阶段(进阶)

一、文件编辑监听事件

1、实现FileEditorManagerListener接口
 @Override
    public void fileOpenedSync(@NotNull FileEditorManager source, @NotNull VirtualFile file, @NotNull Pair<FileEditor[], FileEditorProvider[]> editors) {
        
    }

    @Override
    public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        
    }

    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
        
    }

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        FileEditor[] editors = source.getAllEditors();
    }

2、注册事件
public class MyComponent implements ProjectComponent {

    public MyComponent(@NotNull Project project) {
        MyListenr array = new MyListenr();
        project.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, array);
    }
}

plugin.xml 
<project-components>
  <component>
    <implementation-class>core.MyComponent</implementation-class>
  </component>
</project-components>

    

二、获取文件编辑器的面板

1、获取监听事件的文件编辑对象
public class TestAction implements FileEditorManagerListener {

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        FileEditor[] editors = source.getAllEditors();
        for(int var5 = 0; var5 < editors.length; ++var5) {
            FileEditor editor = editors[var5];
            Intrinsics.checkExpressionValueIsNotNull(editor, "editor");
            inject(editor);
        }
    }

2、从编辑对象中获取编辑面板
private final JPanel getPanel(FileEditor editor) {
        if (!(editor instanceof TextEditor)) {
            // this.logger.debug("I01: Injection failed, only text editors are supported currently.");
            return null;
        } else {
            try {
                JComponent component = editor.getComponent();
                if (component == null) {
                    throw new TypeCastException("null cannot be cast to non-null type javax.swing.JPanel");
                } else {
                    JPanel outerPanel = (JPanel)component;
                    LayoutManager layoutManager = outerPanel.getLayout();
                    if (layoutManager == null) {
                        throw new TypeCastException("null cannot be cast to non-null type java.awt.BorderLayout");
                    } else {
                        BorderLayout outerLayout = (BorderLayout)layoutManager;
                        Component layoutComponent = outerLayout.getLayoutComponent("Center");
                        if (layoutComponent instanceof JBSplitter) {
                            component = ((JBSplitter)layoutComponent).getFirstComponent();
                            if (component == null) {
                                throw new TypeCastException("null cannot be cast to non-null type javax.swing.JPanel");
                            }

                            JPanel editorComp = (JPanel)component;
                            layoutManager = editorComp.getLayout();
                            if (layoutManager == null) {
                                throw new TypeCastException("null cannot be cast to non-null type java.awt.BorderLayout");
                            }

                            layoutComponent = ((BorderLayout)layoutManager).getLayoutComponent("Center");
                        }

                        if (layoutComponent == null) {
                            throw new TypeCastException("null cannot be cast to non-null type javax.swing.JLayeredPane");
                        } else {
                            JLayeredPane pane = (JLayeredPane)layoutComponent;
                            Component component1;
                            JPanel jpanel;
                            if (pane.getComponentCount() > 1) {
                                component1 = pane.getComponent(1);
                                if (component1 == null) {
                                    throw new TypeCastException("null cannot be cast to non-null type javax.swing.JPanel");
                                }

                                jpanel = (JPanel)component1;
                            } else {
                                component1 = pane.getComponent(0);
                                if (component1 == null) {
                                    throw new TypeCastException("null cannot be cast to non-null type javax.swing.JPanel");
                                }

                                jpanel = (JPanel)component1;
                            }

                            JPanel panel = jpanel;
                            layoutManager = panel.getLayout();
                            if (layoutManager == null) {
                                throw new TypeCastException("null cannot be cast to non-null type java.awt.BorderLayout");
                            } else {
                                return panel;
                            }
                        }
                    }
                }
            } catch (ClassCastException var7) {
                Throwable throwable = var7;
                if (throwable == null) {
                    return null;
                    // throw new TypeCastException("null cannot be cast to non-null type java.lang.Throwable");
                } else {
                    throwable.printStackTrace();
                    return null;
                }
            }
        }
    }

  

三、事件集合

1、选择事件:SelectionListener
      SelectionListener selectionListener = (new SelectionListener() {
            @Override
            public final void selectionChanged(SelectionEvent it) {
                Messages.showInfoMessage("1111", "3333");
            }
        });
 
2、文件监听事件:DocumentListener
     DocumentListener documentAdapter= new DocumentAdapter() {
            @Override
            public void documentChanged(@Nullable DocumentEvent documentEvent) {
                Messages.showInfoMessage("1111", "3333");
            }
 
            @Override
            public void beforeDocumentChange(@NotNull DocumentEvent event) {
                 
            }
        };
 
        JTextField textField2=null;
        textField2.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {
            @Override
            public void insertUpdate(javax.swing.event.DocumentEvent e) {
                 
            }
 
            @Override
            public void removeUpdate(javax.swing.event.DocumentEvent e) {
 
            }
 
            @Override
            public void changedUpdate(javax.swing.event.DocumentEvent e) {
 
            }
        });
 
3、组件监听事件:ComponentListener
        ComponentListener componentListener = new ComponentAdapter() {
            @Override
            public void componentResized(@Nullable ComponentEvent componentEvent) {
                Messages.showInfoMessage("1111", "3333");
            }
        };
        new JPanel().addComponentListener(componentListener);
 
 
4、鼠标点击监听器:MouseListener
 
5、鼠标移动事件:MouseMotionListener
 
6、鼠标滚轮事件:MouseWheelListener

7、文件编辑事件监听器:FileEditorManagerListener

8、编辑器视图监听器VisibleAreaListener
public class TestAction implements FileEditorManagerListener {

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        FileEditor[] editors = source.getAllEditors();
        for(int var5 = 0; var5 < editors.length; ++var5) {
            FileEditor fileEditor = editors[var5];
            Editor editor = ((TextEditor) fileEditor).getEditor();
            VisibleAreaListener visibleAreaListener = new VisibleAreaListener() {
                @Override
                public void visibleAreaChanged(@NotNull VisibleAreaEvent visibleAreaEvent) {

                }
            };
            editor.getScrollingModel().addVisibleAreaListener(visibleAreaListener);
        }

  

四、文本编辑器滚动到指定位置

public class TestAction implements FileEditorManagerListener {

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        FileEditor[] editors = source.getAllEditors();
        for(int var5 = 0; var5 < editors.length; ++var5) {
            FileEditor fileEditor = editors[var5];
            Editor editor = ((TextEditor) fileEditor).getEditor();
            // 滚动到第20字符的位置
            editor.getScrollingModel().scrollVertically(20);
        }

    

五、启用/禁用编辑器动画

public class TestAction implements FileEditorManagerListener {

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        FileEditor[] editors = source.getAllEditors();
        for(int var5 = 0; var5 < editors.length; ++var5) {
            FileEditor fileEditor = editors[var5];
            Editor editor = ((TextEditor) fileEditor).getEditor();
            // 滚动到第20字符的位置
            editor.getScrollingModel().scrollVertically(20);
            editor.getScrollingModel().disableAnimation();
            editor.getScrollingModel().enableAnimation();

 

五、改变鼠标形状

  JPanel jpanel = new JPanel(new BorderLayout());
                    jpanel.setPreferredSize(new Dimension(800, 1000));
                    jpanel.addMouseMotionListener(new MouseMotionListener() {
                        @Override
                        public void mouseDragged(MouseEvent e) {

                        }
                        @Override
                        public void mouseMoved(MouseEvent e) {
                            if (e.getX() < 200) {
                                jpanel.setCursor(new Cursor(10));
                            } else if (e.getX() < 400) {
                                jpanel.setCursor(new Cursor(Cursor.HAND_CURSOR));
                            } else  {
                                jpanel.setCursor(new Cursor(0));
                            }
                        }
                    });

  

六、获取语法的高亮颜色

public class TestAction implements FileEditorManagerListener {

    private Project project;

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        FileEditor[] editors = source.getAllEditors();
        for(int var5 = 0; var5 < editors.length; ++var5) {
            FileEditor fileEditor = editors[var5];
            getColor(fileEditor);
}

private final int getColor(FileEditor fileEditor) {
        Editor editor = ((TextEditor) fileEditor).getEditor();
        EditorColorsScheme colorScheme = editor.getColorsScheme();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        final SyntaxHighlighter hl = SyntaxHighlighterFactory.getSyntaxHighlighter(file.getLanguage(), this.project, file.getVirtualFile());
        Lexer lexer = hl.getHighlightingLexer();
        final String text = editor.getDocument().getText();
        lexer.start(text);
        for(IElementType tokenType = lexer.getTokenType(); tokenType != null; tokenType = lexer.getTokenType()) {
            int color = colorScheme.getDefaultForeground().getRGB();
            TextAttributesKey[] attributes = hl.getTokenHighlights(tokenType);

            for(int var8 = 0; var8 < attributes.length; ++var8) {
                TextAttributesKey attribute = attributes[var8];
                TextAttributes attr = colorScheme.getAttributes(attribute);
                if (attr != null) {
                    Color tmp = attr.getForegroundColor();
                    if (tmp != null) {
                        color = tmp.getRGB();
                        return color;
                    }
                }
            }

            BufferedImage bufferedImage = new BufferedImage();
            int[] array = new int[]{
                    (color & 16711680) >> 16, (color & '\uff00') >> 8, color & 255, (int) (0 * (float) 255)
            };
            bufferedImage.getRaster().setPixel(x, y, array);
        }
        return 0;
    }

  

七、鼠标悬停时获取鼠标所在的的元素

实现接口DocumentationProviderEx

public class TranTest extends DocumentationProviderEx {
    /**
     * 在鼠标位置显示字符
     */
    @Nullable
    @Override
    public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) {
        return "originalDoc";
    }
    
}

  <extensions defaultExtensionNs="com.intellij">
    <!-- Add your extensions here -->
    <lang.documentationProvider
            language="JAVA" order="first"
            implementationClass="core.TranTest"/>
  </extensions>

  

八、在浏览器打开

     Desktop.getDesktop().browse(uri);

  

九:java swing事件监听

registerKeyboardAction

getRootPane().registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AboutDialog.this.dispose();
            }
        }, KeyStroke.getKeyStroke(27, 0), 2);



addActionListener
buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AboutDialog.this.onOK();
            }
        });

addHyperlinkListener
    private class BrowseHyperlinkListener implements HyperlinkListener {
        private BrowseHyperlinkListener() {
        }

        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == EventType.ACTIVATED && Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(e.getURL().toURI());
                } catch (IOException var3) {
                    AboutDialog.this.logger.warn("Exception browsing to " + e.getURL().toExternalForm() + " : " + var3);
                } catch (URISyntaxException var4) {
                    AboutDialog.this.logger.warn("Incorrect URI syntax " + e.getURL().toExternalForm() + " : " + var4);
                }
            }

        }
    }



addAncestorListener
        this.toolWindow.getComponent().addAncestorListener(this.plantUmlAncestorListener);
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.plantuml.idea.toolwindow.listener;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import org.plantuml.idea.lang.settings.PlantUmlSettings;
import org.plantuml.idea.rendering.LazyApplicationPoolExecutor.Delay;
import org.plantuml.idea.rendering.RenderCommand.Reason;
import org.plantuml.idea.toolwindow.PlantUmlToolWindow;

public class PlantUmlAncestorListener implements AncestorListener {
    private static Logger logger = Logger.getInstance(PlantUmlAncestorListener.class);
    private final PlantUmlSettings settings;
    private PlantUmlToolWindow plantUmlToolWindow;
    private Project project;

    public PlantUmlAncestorListener(PlantUmlToolWindow plantUmlToolWindow, Project project) {
        this.plantUmlToolWindow = plantUmlToolWindow;
        this.project = project;
        this.settings = PlantUmlSettings.getInstance();
    }

    public void ancestorAdded(AncestorEvent ancestorEvent) {
        logger.debug("ancestorAdded ", new Object[]{this.project.getName()});
        if (this.settings.isAutoRender()) {
            this.plantUmlToolWindow.renderLater(Delay.POST_DELAY, Reason.FILE_SWITCHED);
        }

    }

    public void ancestorRemoved(AncestorEvent event) {
    }

    public void ancestorMoved(AncestorEvent event) {
    }
}








addAdjustmentListener
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent adjustmentEvent) {
                if (!adjustmentEvent.getValueIsAdjusting()) {
                    RenderCacheItem displayedItem = PlantUmlToolWindow.this.getDisplayedItem();
                    if (displayedItem != null && !displayedItem.getRenderResult().hasError()) {
                        PlantUmlToolWindow.this.lastValidVerticalScrollValue = adjustmentEvent.getValue();
                    }
                }

            }
        });

scrollPane.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
            public void adjustmentValueChanged(AdjustmentEvent adjustmentEvent) {
                if (!adjustmentEvent.getValueIsAdjusting()) {
                    RenderCacheItem displayedItem = PlantUmlToolWindow.this.getDisplayedItem();
                    if (displayedItem != null && !displayedItem.getRenderResult().hasError()) {
                        PlantUmlToolWindow.this.lastValidHorizontalScrollValue = adjustmentEvent.getValue();
                    }
                }

            }
        });


addMouseWheelListener
        panel.addMouseWheelListener(new MouseWheelListener() {
            public void mouseWheelMoved(MouseWheelEvent e) {
                if (e.isControlDown()) {
                    PlantUmlToolWindow.this.setZoom(Math.max(PlantUmlToolWindow.this.zoom - e.getWheelRotation() * 10, 1));
                } else {
                    e.setSource(PlantUmlToolWindow.this.scrollPane);
                    PlantUmlToolWindow.this.scrollPane.dispatchEvent(e);
                }

            }

  

 

posted @ 2020-11-07 23:37  antlord  阅读(2236)  评论(0编辑  收藏  举报