如何在按下箭头键时阻止JScrollPane滚动

时间:2012-07-18 01:41:08

标签: java swing jscrollpane

我在JScrollPane中有一个JPanel,而JPanel在一个函数中使用了箭头键。令人讨厌的是,当按下箭头键时,JScrollPane会滚动。如何使它在按下箭头键时不滚动JScrollPane?

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分: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";

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