Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't focus JScrollPane?

I'm having issues giving focus to a JScrollPane. I'm trying to do this when the window is created so that I can try out the key bindings I'm working on. Everything shows up where it's supposed to be and at the correct size. What I've got looks like this:

import java.awt.*;
import java.swing.*;

public class MyInterface extends JFrame {
   public MyInterface() {}

   public static void main(String[] args) {
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }

   private static void createAndShowGUI() {
      // define custom table model
      JTable table = new JTable(model);
      MyScrollPane scrollPane = new MyScrollPane(table);
      MyInterface frame = new MyInterface();
      scrollPane.setPreferredSize(new Dimension(512, 512));
      frame.getContentPane().add(scrollPane);
      frame.pack();
      frame.setVisible();
      scrollPane.requestFocus();
   }
}

public class MyScrollPane extends JScrollPane implements KeyListener {
   public MyScrollPane(Component view) {
      super(view, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
   }

   // key event processing
}

I tried adding a window listener to the frame which would request focus for scrollPane after the window was finished opening, but it didn't help. Any ideas?

EDIT: Thought I should mention that scrollPane.isFocusable() and scrollPane.isRequestFocusEnabled both return true, so I should be able to give it focus.

EDIT: It seems I'm unable to give focus to anything (frame, table, etc.), so there's some other problem here. No matter what I try, this displays null:

Component compFocusOwner =   KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
System.out.println("focus owner: " + compFocusOwner);
like image 331
bendicott Avatar asked Feb 17 '26 12:02

bendicott


1 Answers

I think that not possible to set the Focus to the JScrolPane, but set Focus to the JComponent, which is place into JScrolPane couldn't be problem

    Runnable doRun = new Runnable() {

        @Override
        public void run() {
            myComponent.requestFocus();//requestFocusInWindow
            myComponent.grabFocus();
        }
    };
    SwingUtilities.invokeLater(doRun);
like image 174
mKorbel Avatar answered Feb 19 '26 01:02

mKorbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!