简体   繁体   中英

JLabel keeps speeding up on each List Selection

list.getSelectionModel().addListSelectionListener(e -> {
    timer = new Timer( DELAY, new ActionListener()
    {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            StockItem p = list.getSelectedValue();
            label.setText(p.toString2());
            label.setLocation(label.getLocation().x+1, label.getLocation().y);
            if(label.getLocation().x >= frame.getWidth()) {
                label.setLocation(0-label.getWidth(),label.getLocation().y);
            }    
        }

    });
    timer.start();
});

I created a list selection listener to check which current items are being selected inside of a JList, and whatever item is being selected will call a toString() method in another class and set this as the text for a JLabel. However, I just implemented moving text on my JLabel and every time an item in the JList is selected, the speed of the JLabel will increase. I would like it so the speed stays constant but i'm not sure how to do that.

The part of the code that controls the speed is label.setLocation(label.getLocation().x+1, label.getLocation().y);

Any explanations would be very appreciated thank you

every time an item in the JList is selected, the speed of the JLabel will increase.

Because your code starts another Timer with each selection.

A Timer will keep running until you stop it. Since you never stop it you will have multiple Timers running at the same time.

You want to define your Timer outside of the ListSelectionListener.

Then the logic inside the listener becomes something like:

(if !timer.isRunning())
    timer.start();

Or the question is do you even need the ListSelectionListener?

You could just start the Timer automatically when you class is created. Each time it fires the logic will get the selected value.

Of course with this approach you need to make sure the getSelectedValue() method doesn't return null (as no item will be selected when the GUI is first displayed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM