javatextnetbeansjlabelgraphical-programming

How to create running text with jlabel?


Let's just say i have a jlabel with a text in it. And i want the text keep changing every second to the left just like running text on the billboard.

Is it possible? if yes, how?


Solution

  • You should use javax.swing.Timer to schedule JLabel updates. Please, see simplified code snippet below:

    JFrame frame = new JFrame("Test");
    frame.setSize(300, 300);
    JLabel label = new JLabel("This is text!!!");
    frame.add(label);
    frame.setVisible(true);
    
    final int labelWidth = 300;
    final AtomicInteger labelPadding = new AtomicInteger();
    Timer timer = new Timer(20, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            label.setBorder(new EmptyBorder(0, labelPadding.getAndIncrement() % labelWidth, 0, 0));
        }
    });
    timer.start();
    

    Note that AtomicInteger is not necessary, but you need some final holder to be able to use it inside inner class or lambda.