How to prevent JScrollPane from scrolling when you press the arrow keys

I have a JPanel inside a JScrollPane, and a JPanel uses the arrow keys in a function. It annoys him that the JScrollPane scrolls when you press the arrow keys. How to make JScrollPane not scroll when I press the arrow keys?

+4
source share
2 answers

It may be too much, but you can try the following:

UIManager.getDefaults().put("ScrollPane.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] {})); 

You can also replace action around the world:

 InputMap actionMap = (InputMap) UIManager.getDefaults().get("ScrollPane.ancestorInputMap"); actionMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { }}); actionMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { }}); 

Following @MadProgrammer's suggestion, you can replace specific actions for keyboard arrows. Use the names unitScrollRight and unitScrollDown :

 scrollPane.getActionMap().put("unitScrollRight", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { }}); scrollPane.getActionMap().put("unitScrollDown", new AbstractAction(){ @Override public void actionPerformed(ActionEvent e) { }}); 
+6
source

I think you will have to replace the link to the input / action card

 ActionMap am = scrollPane.getActionMap(); am.remove("scrollDown"); am.remove("scrollUp"); 

The keys I extracted from BasicScrollPaneUI so that they can change between the user interface, but the idea should work

UPDATE

Well, it sucked. I was hoping to get away.

  InputMap im = comp.getInputMap(); im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "scrollDown"); ActionMap am = comp.getActionMap(); am.put("scrollDown", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.println(e.getSource() + " - no go down"); } }); 

Should void the action. I got it to work with JList and big JPanel

While I am here:

  private static final String SCROLL_UP = "scrollUp"; private static final String SCROLL_DOWN = "scrollDown"; private static final String SCROLL_HOME = "scrollHome"; private static final String SCROLL_END = "scrollEnd"; private static final String UNIT_SCROLL_UP = "unitScrollUp"; private static final String UNIT_SCROLL_DOWN = "unitScrollDown"; private static final String SCROLL_LEFT = "scrollLeft"; private static final String SCROLL_RIGHT = "scrollRight"; private static final String UNIT_SCROLL_LEFT = "unitScrollLeft"; private static final String UNIT_SCROLL_RIGHT = "unitScrollRight"; 

Are other input / action card commands

+4
source

All Articles