cleanup (inspection "Java | Class structure | Utility class is not 'final'")
[idea/community.git] / platform / platform-api / src / com / intellij / util / EditSourceOnEnterKeyHandler.java
1 // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
2 package com.intellij.util;
3
4 import com.intellij.ide.DataManager;
5 import com.intellij.openapi.actionSystem.CommonDataKeys;
6 import com.intellij.openapi.actionSystem.DataContext;
7 import com.intellij.openapi.project.Project;
8 import org.jetbrains.annotations.NotNull;
9 import org.jetbrains.annotations.Nullable;
10
11 import javax.swing.*;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.ActionListener;
14 import java.awt.event.KeyAdapter;
15 import java.awt.event.KeyEvent;
16
17 public final class EditSourceOnEnterKeyHandler{
18   public static void install(@NotNull JTree tree) {
19     tree.addKeyListener(
20       new KeyAdapter() {
21         @Override
22         public void keyPressed(KeyEvent e) {
23           if (KeyEvent.VK_ENTER != e.getKeyCode()) return;
24
25           DataContext dataContext = DataManager.getInstance().getDataContext(tree);
26           Project project = CommonDataKeys.PROJECT.getData(dataContext);
27           if (project == null) return;
28
29           OpenSourceUtil.openSourcesFrom(dataContext, false);
30         }
31       }
32     );
33   }
34
35   public static void install(@NotNull JComponent component, @Nullable Runnable whenPerformed) {
36     component.registerKeyboardAction(new ActionListener() {
37       @Override
38       public void actionPerformed(ActionEvent e) {
39         DataContext dataContext = DataManager.getInstance().getDataContext(component);
40
41         OpenSourceUtil.openSourcesFrom(dataContext, true);
42         if (whenPerformed != null) whenPerformed.run();
43       }
44     }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
45   }
46 }