Java Code Examples for javax.swing.FocusManager

The following examples show how to use javax.swing.FocusManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: openjdk-jdk9   Source File: FocusTraversal.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void isFocusOwner(Component queriedFocusOwner,
        String direction)
        throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            Component actualFocusOwner
                    = FocusManager.getCurrentManager().getFocusOwner();
            if (actualFocusOwner != queriedFocusOwner) {
                frame.dispose();
                throw new RuntimeException(
                        "Focus component is wrong after " + direction
                        + " direction ");

            }
        }
    });
}
 
Example 2
Source Project: Digital   Source File: GuiTester.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void run(GuiTester guiTester) throws Exception {
    Window activeWindow = FocusManager.getCurrentManager().getActiveWindow();
    if (activeWindow == null || !expectedClass.isAssignableFrom(activeWindow.getClass())) {
        Thread.sleep(1000);
        activeWindow = FocusManager.getCurrentManager().getActiveWindow();
    }
    Assert.assertNotNull("no java window on top!", activeWindow);

    Assert.assertTrue(getClass().getSimpleName()
                    + ": wrong dialog on top! expected: <"
                    + expectedClass.getSimpleName()
                    + "> but was: <"
                    + activeWindow.getClass().getSimpleName()
                    + ">",
            expectedClass.isAssignableFrom(activeWindow.getClass()));
    try {
        checkWindow(guiTester, (W) activeWindow);
    } catch (Exception e) {
        Thread.sleep(1000);
        checkWindow(guiTester, (W) activeWindow);
    }
}
 
Example 3
public DefaultHeaderComponent( final String title, final Insets insets, final double darkeningFactor ) {
  this.darkeningFactor = darkeningFactor;

  setLayout( new BorderLayout() );
  setOpaque( false );
  setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, getDarkerColor( getBackground() ) ) );
  setGradientColors( new Color[] { getDarkerColor( getBackground() ), getBackground() } );
  setDirection( GradientPanel.Direction.DIRECTION_LEFT );

  final JLabel headerLabel = new JLabel( title );
  headerLabel.setBorder( BorderFactory.createEmptyBorder( insets.top, insets.left, insets.bottom, insets.right ) );
  add( headerLabel, BorderLayout.CENTER );

  final FocusManager currentManager = FocusManager.getCurrentManager();
  target = new FocusManagerChangeHandler();
  currentManager.addPropertyChangeListener( PERMANENT_FOCUS_OWNER, target );
}
 
Example 4
Source Project: consulo   Source File: SingleInspectionProfilePanel.java    License: Apache License 2.0 6 votes vote down vote up
private static void setConfigPanel(final JPanel configPanelAnchor, final ScopeToolState state) {
  configPanelAnchor.removeAll();
  final JComponent additionalConfigPanel = state.getAdditionalConfigPanel();
  if (additionalConfigPanel != null) {
    final JScrollPane pane = ScrollPaneFactory.createScrollPane(additionalConfigPanel, SideBorder.NONE);
    FocusManager.getCurrentManager().addPropertyChangeListener("focusOwner", new PropertyChangeListener() {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
        if (!(evt.getNewValue() instanceof JComponent)) {
          return;
        }
        final JComponent component = (JComponent)evt.getNewValue();
        if (component.isAncestorOf(pane)) {
          pane.scrollRectToVisible(component.getBounds());
        }
      }
    });
    configPanelAnchor.add(pane);
  }
  UIUtil.setEnabled(configPanelAnchor, state.isEnabled(), true);
}
 
Example 5
Source Project: darklaf   Source File: DarkPanelPopupUI.java    License: MIT License 5 votes vote down vote up
@Override
public void eventDispatched(final AWTEvent event) {
    if (event.getID() == FocusEvent.FOCUS_GAINED) {
        Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
        if (focusOwner instanceof JTabFrame) return;
        if (focusOwner instanceof JRootPane) return;
        boolean focus = DarkUIUtil.hasFocus(popupComponent);
        if (popupComponent.getTabFrame() != null) {
            Container container = popupComponent.getTabFrame().getContentPane()
                                                .getContainer(popupComponent.getAlignment());
            focus = focus || DarkUIUtil.hasFocus(container);
        }
        setHeaderBackground(focus);
    }
}
 
Example 6
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (placeholder != null && !placeholder.isEmpty() && getText().isEmpty() && !(FocusManager.getCurrentKeyboardFocusManager().getFocusOwner() == this)) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setColor(new Color(0x80000000, true));
        int deltaY = (int) ((getIOSWidget().frame().getSize().getHeight() - placeholderMetrics.getHeight()) / 2f);
        TextLayout layout = new TextLayout(placeholder, g2.getFont(), g2.getFontRenderContext());
        g2.drawString(placeholder, 5, deltaY + layout.getAscent());
        g2.dispose();
    }
}
 
Example 7
Source Project: ghidra   Source File: DockableComponent.java    License: Apache License 2.0 5 votes vote down vote up
private Component findFocusedComponent() {
	if (focusedComponent != null && focusedComponent.isShowing()) {
		return focusedComponent;
	}

	DefaultFocusManager dfm = (DefaultFocusManager) FocusManager.getCurrentManager();
	Component component = dfm.getComponentAfter(this, this);

	// component must be a child of this DockableComponent
	if (component != null && SwingUtilities.isDescendingFrom(component, this)) {
		return component;
	}
	return null;
}
 
Example 8
Source Project: netbeans   Source File: ResultView.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isFocused() {
    ResultViewPanel rvp = getCurrentResultViewPanel();
    if (rvp != null) {
        Component owner = FocusManager.getCurrentManager().getFocusOwner();
        return owner != null && SwingUtilities.isDescendingFrom(owner, rvp);
    } else {
        return false;
    }
}
 
Example 9
Source Project: netbeans   Source File: NbPresenter.java    License: Apache License 2.0 5 votes vote down vote up
/** Requests focus for <code>currentMessage</code> component.
 * If it is of <code>JComponent</code> type it tries default focus
 * request first. */
private void requestFocusForMessage() {
    Component comp = currentMessage;

    if(comp == null) {
        return;
    }

    if (/*!Constants.AUTO_FOCUS &&*/ FocusManager.getCurrentManager().getActiveWindow() == null) {
        // Do not steal focus if no Java window have it
        Component defComp = null;
        Container nearestRoot =
            (comp instanceof Container && ((Container) comp).isFocusCycleRoot()) ? (Container) comp : comp.getFocusCycleRootAncestor();
        if (nearestRoot != null) {
            defComp = nearestRoot.getFocusTraversalPolicy().getDefaultComponent(nearestRoot);
        }
        if (defComp != null) {
            defComp.requestFocusInWindow();
        } else {
            comp.requestFocusInWindow();
        }
    } else {
        if (!(comp instanceof JComponent)
            || !((JComponent)comp).requestDefaultFocus()) {

            comp.requestFocus();
        }
    }
}
 
Example 10
Source Project: netbeans   Source File: NavigatorController.java    License: Apache License 2.0 5 votes vote down vote up
public void actionPerformed (ActionEvent evt) {
    Component focusOwner = FocusManager.getCurrentManager().getFocusOwner();
    // move focus away only from navigator AWT children,
    // but not combo box to preserve its ESC functionality
    if (lastActivatedRef == null ||
        focusOwner == null ||
        !SwingUtilities.isDescendingFrom(focusOwner, navigatorTC.getTopComponent()) ||
        focusOwner instanceof JComboBox) {
        return;
    }
    TopComponent prevFocusedTc = lastActivatedRef.get();
    if (prevFocusedTc != null) {
        prevFocusedTc.requestActive();
    }
}
 
Example 11
Source Project: Digital   Source File: ScreenShots.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run(GuiTester guiTester) throws Exception {
    Window main = FocusManager.getCurrentManager().getActiveWindow();
    while (!(main instanceof Main)) {
        main = (Window) main.getParent();
        if (main == null)
            throw new RuntimeException("Main not found!");
    }

    BufferedImage image = guiTester.getRobot().createScreenCapture(main.getBounds());
    File file = new File(Resources.getRoot().getParentFile().getParentFile().getParentFile(), name);
    ImageIO.write(image, "png", file);
}
 
Example 12
Source Project: Digital   Source File: GuiTester.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Container getBaseContainer() {
    Container baseContainer = FocusManager.getCurrentManager().getActiveWindow();
    if (baseContainer instanceof JDialog)
        baseContainer = ((JDialog) baseContainer).getContentPane();
    else if (baseContainer instanceof JFrame)
        baseContainer = ((JFrame) baseContainer).getContentPane();
    return baseContainer;
}
 
Example 13
Source Project: Digital   Source File: GuiTester.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run(GuiTester guiTester) throws Exception {
    Point p = new Point(x, y);

    Component t = searchComponent(FocusManager.getCurrentManager().getActiveWindow(), target);
    if (t == null)
        throw new RuntimeException("Component " + target.getSimpleName() + " not found!");

    SwingUtilities.convertPointToScreen(p, t);
    Thread.sleep(100);
    guiTester.getRobot().mouseMove(p.x, p.y);
    Thread.sleep(100);
    cpi.checkColor(guiTester.getRobot().getPixelColor(p.x, p.y));
}
 
Example 14
Source Project: Digital   Source File: GuiTester.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run(GuiTester gt) throws Exception {
    Component baseContainer = searchComponent(FocusManager.getCurrentManager().getActiveWindow(), target);
    if (baseContainer == null)
        throw new RuntimeException("Component " + target.getSimpleName() + " not found!");

    label.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                PointerInfo inf = MouseInfo.getPointerInfo();
                Point p = inf.getLocation();
                Color col = gt.getRobot().getPixelColor(p.x, p.y);
                SwingUtilities.convertPointFromScreen(p, baseContainer);
                System.out.print(".add(new GuiTester.ColorPicker(");
                System.out.print(target.getSimpleName());
                System.out.print(".class, ");
                System.out.print(p.x + ", " + p.y);
                System.out.print(", new Color(");
                System.out.print(col.getRed() + "," + col.getGreen() + "," + col.getBlue());
                System.out.println(")))");
            } else if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE)
                System.exit(1);
        }
    });
    setVisible(true);
}
 
Example 15
Source Project: weblaf   Source File: DefaultFocusTracker.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs new {@link DefaultFocusTracker}.
 *
 * @param component         tracked {@link JComponent}
 * @param uniteWithChildren whether or not tracked {@link JComponent} and its children should be counted as a single focusable unit
 */
public DefaultFocusTracker ( @NotNull final JComponent component, final boolean uniteWithChildren )
{
    super ();
    this.component = component;
    this.uniteWithChildren = uniteWithChildren;
    this.focusableChildren = null;
    this.enabled = true;
    this.focused = isInvolved ( component, FocusManager.getCurrentManager ().getFocusOwner () );
}
 
Example 16
Source Project: weblaf   Source File: SwingUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns whether component or any of its children has focus or not.
 *
 * @param component component to process
 * @return true if component or any of its children has focus, false otherwise
 */
public static boolean hasFocusOwner ( @Nullable final Component component )
{
    final Component focusOwner = FocusManager.getCurrentManager ().getFocusOwner ();
    return component != null && component == focusOwner ||
            component instanceof Container && ( ( Container ) component ).isAncestorOf ( focusOwner );
}
 
Example 17
Source Project: netbeans   Source File: NotifyExcPanel.java    License: Apache License 2.0 4 votes vote down vote up
/** Updates the visual state of the dialog.
*/
private void update () {
    // JST: this can be improved in future...
    boolean isLocalized = current.isLocalized();

    boolean repack;
    boolean visNext = next.isVisible();
    boolean visPrev = previous.isVisible();
    next.setVisible (exceptions.existsNextElement());
    previous.setVisible (exceptions.existsPreviousElement());
    repack = next.isVisible() != visNext || previous.isVisible() != visPrev;

    if (showDetails) {
        Mnemonics.setLocalizedText(details, org.openide.util.NbBundle.getBundle(NotifyExcPanel.class).getString("CTL_Exception_Hide_Details"));
        details.getAccessibleContext().setAccessibleDescription(
            org.openide.util.NbBundle.getBundle(NotifyExcPanel.class).getString("ACSD_Exception_Hide_Details"));
    } else {
        Mnemonics.setLocalizedText(details, org.openide.util.NbBundle.getBundle(NotifyExcPanel.class).getString("CTL_Exception_Show_Details"));
        details.getAccessibleContext().setAccessibleDescription(
            org.openide.util.NbBundle.getBundle(NotifyExcPanel.class).getString("ACSD_Exception_Show_Details"));
    }

    //    setText (current.getLocalizedMessage ());
    String title = org.openide.util.NbBundle.getBundle(NotifyExcPanel.class).getString("CTL_Title_Exception");

    if (showDetails) {
        descriptor.setMessage (this);
        
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // XXX #28191: some other piece of code should underline these, etc.
                    StringWriter wr = new StringWriter();
                    current.printStackTrace(new PrintWriter(wr, true));
                    output.setText(wr.toString());
                    output.getCaret().setDot(0);
                    if (!AUTO_FOCUS && FocusManager.getCurrentManager().getActiveWindow() == null) {
                        // Do not steal focus if no Java window have it
                        output.requestFocusInWindow();
                    } else {
                        output.requestFocus ();
                    }
            }
        });
    } else {
        if (isLocalized) {
            String msg = current.getLocalizedMessage ();
            if (msg != null) {
                descriptor.setMessage (msg);
            }
        } else {
            ResourceBundle curBundle = NbBundle.getBundle (NotifyExcPanel.class);
            if (current.getSeverity() == Level.WARNING) {
                // less scary message for warning level
                descriptor.setMessage (
                    java.text.MessageFormat.format(
                        curBundle.getString("NTF_ExceptionWarning"),
                        new Object[] {
                            current.getClassName ()
                        }
                    )
                );
                title = curBundle.getString("NTF_ExceptionWarningTitle"); // NOI18N
            } else {
                // emphasize user-non-friendly exceptions
                //      if (this.getMessage() == null || "".equals(this.getMessage())) { // NOI18N
                descriptor.setMessage (
                    java.text.MessageFormat.format(
                        curBundle.getString("NTF_ExceptionalException"),
                        new Object[] {
                            current.getClassName (),
                            CLIOptions.getLogDir ()
                        }
                    )
                );

                title = curBundle.getString("NTF_ExceptionalExceptionTitle"); // NOI18N
            }
        }
    }

    descriptor.setTitle (title);
    if (repack) {
        dialog.pack();
    }
   
}
 
Example 18
Source Project: Digital   Source File: GuiTester.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run(GuiTester guiTester) {
    Window activeWindow = FocusManager.getCurrentManager().getActiveWindow();
    Assert.assertNotNull("no java window on top!", activeWindow);
    activeWindow.dispose();
}
 
Example 19
public void componentShown( final ComponentEvent e ) {
  FocusManager.getCurrentManager().focusNextComponent( e.getComponent() );
}
 
Example 20
public void dispose() {
  FocusManager.getCurrentManager().removePropertyChangeListener( PERMANENT_FOCUS_OWNER, target );
}
 
Example 21
Source Project: javamelody   Source File: MSwingUtilities.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Retourne le focusOwner permanent.<br/>
 * Le focusOwner permanent est défini comme le dernier Component à avoir reçu un événement FOCUS_GAINED permanent.<br/>
 * Le focusOwner et le focusOwner permanent sont équivalent sauf si un changement temporaire de focus<br/>
 * est en cours. Si c'est le cas, le focusOwner permanent redeviendra &galement<br/>
 * le focusOwner à la fin de ce changement de focus temporaire.
 *
 * @return Component
 */
public static Component getPermanentFocusOwner() {
	// return new DefaultKeyboardFocusManager().getPermanentFocusOwner();
	return FocusManager.getCurrentManager().getPermanentFocusOwner();
}
 
Example 22
Source Project: javamelody   Source File: MSwingUtilities.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Retourne la fenêtre possédant le focus.
 *
 * @return Component
 */
public static Window getFocusedWindow() {
	// return new DefaultKeyboardFocusManager().getFocusedWindow();
	return FocusManager.getCurrentManager().getFocusedWindow();
}