ASE Home Page Products Download Purchase Support About ASE
ChartDirector Support
Forum HomeForum Home   SearchSearch

Message ListMessage List     Post MessagePost Message

  How to scroll a Java Swing XYChart with arrow keys
Posted by Geoff Harris on Jan-07-2018 20:11
Hi folks

Didn't spot any code for this in the forum, so thought I'd post a solution in case anyone finds it useful. I'm using this on a scrolling finance chart with a timeline and scroll bar. Seems to work well enough, but I'm a Swing newbie so any suggestions for improvements are welcome.

There doesn't seem to be any need to check for overflow if you scroll beyond the min and max values - the component seems to handle that internally.

First, set up a key event dispatcher in your initialisation code:

>>>>>
// Set up key event dispatcher for scrolling the chart with arrow keys
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            @Override
            public boolean dispatchKeyEvent(KeyEvent ke) {
                chartViewer1_KeyEventHandler(ke);
                return false;
            }
        });
>>>>>

Then set up your event handler:

>>>>>
    /**
     * Key event handler - for scrolling the main chart with arrow keys
     *
     * Shift-LeftArrow / Shift-RightArrow to start and end of chart
     * Control-LeftArrow / Control-RightArrow to scroll 10 bars
     * LeftArrow / RightArrow to scroll 1 bar
     */
    private void chartViewer1_KeyEventHandler(KeyEvent ke){

        final int barWidth = hScrollBar1.getMaximum() / timeStamps.length;
        final int fastMultiple = 10;

        if (ke.getID() == KeyEvent.KEY_PRESSED) {

            if (ke.isShiftDown() && ke.getKeyCode() == KeyEvent.VK_LEFT) {

                hScrollBar1.setValue(hScrollBar1.getMinimum());

            } else if (ke.isShiftDown() && ke.getKeyCode() == KeyEvent.VK_RIGHT) {

                hScrollBar1.setValue(hScrollBar1.getMaximum());

            } else if (ke.isControlDown() && ke.getKeyCode() == KeyEvent.VK_LEFT) {

                final int val = hScrollBar1.getValue();
                hScrollBar1.setValue(val - (barWidth * fastMultiple));

            } else if (ke.isControlDown() && ke.getKeyCode() == KeyEvent.VK_RIGHT) {

                final int val = hScrollBar1.getValue();
                hScrollBar1.setValue(val + (barWidth * fastMultiple));

            } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {

               final int val = hScrollBar1.getValue();
               hScrollBar1.setValue(val - barWidth);

            } else if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {

                final int val = hScrollBar1.getValue();
                hScrollBar1.setValue(val + barWidth);
            }
        }
    }
>>>>>