Question

i want to make a java GUI program. it contains a jScrollpane which contains a big jPanel. the jPanel it's self contains lots of Swing components like jButtons, jPanels and... .what i want is when the user clicks on a jButton the jScrollpane starts to scroll to the end of big panel with a constant velocity. something like android OS. as I know I must know how to make animation with java to solve this problem, I tried to solve that simply with Threads but it is not possible and it seems that swing needs more specific use of threads... could you please give me your ideas? is it related to Swingworker ? really really critical...:(

Update: I tried to solve that with timer class:

       ActionListener action = new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if (mainContainerScrollPane.getHorizontalScrollBar().getValue() == mainContainerScrollPane.getHorizontalScrollBar().getMaximum())
                timer.stop();
            mainContainerScrollPane.getHorizontalScrollBar().setValue(mainContainerScrollPane.getHorizontalScrollBar().getValue() + 5);
            mainContainerScrollPane.repaint();
        }
    };

    timer = new Timer(10, action);
    timer.start();

the problem now is the animation is not smoothly done. i mean it scrolls smoothly on but as it reaches to a specific place it's speed comes down. why?

Was it helpful?

Solution

Generally speaking, any event that changes a GUI component should be run on the event dispatch thread (EDT). You can use a swing Timer to fire repeated events on the EDT as explained in this tutoria. http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html. On the timer event, you can increment the scrollbar's value to whatever the new position should be. Repeat this with the same increment to get the effect you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top