5

我在 JScrollPane 中有一个 JPanel,并且 JPanel 在函数中使用箭头键。按下箭头键时 JScrollPane 滚动,这很烦人。如何使 JScrollPane 在按下箭头键时不滚动?

4

2 回答 2

7

可能太多了,但你可以试试这个:

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

您也可以全局替换操作:

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) {
    }});

按照@MadProgrammer 的建议,您可以替换键盘箭头的特定操作。使用unitScrollRightunitScrollDown动作名称:

scrollPane.getActionMap().put("unitScrollRight", new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e) {
    }});
scrollPane.getActionMap().put("unitScrollDown", new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e) {
    }});
于 2012-07-18T03:06:21.053 回答
4

我认为您将不得不替换输入/操作映射参考

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

我从 BasicScrollPaneUI 中提取的键,因此它们可能会在 UI 之间发生变化,但这个想法应该可行

更新

好吧,那糟透了。我希望摆脱简单。

    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");

        }
    });

应该导致动作无效。我让它与 JList 和大型 JPanel 一起工作

当我在这里时:

    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";

其他输入/动作映射命令是

于 2012-07-18T01:53:36.870 回答