Rectangle 27 2

You can use an executor to update that periodically. Something like this:

ScheduledExecutorService e= Executors.newSingleThreadScheduledExecutor();
e.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    // do stuff
    SwingUtilities.invokeLater(new Runnable() {
       // of course, you could improve this by moving dateformat variable elsewhere
       DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
       Date date = new Date();
       CurrentDateTime.setText(dateandtime.format(date));
    });
  }
}, 0, 1, TimeUnit.SECONDS);

Thank you for your help! this works perfectly; however just to help any one else, an @Override should be invoked so that the code can run well :)

swing - Java timer, update every second - Stack Overflow

java swing date time timer
Rectangle 27 1

First define a TimerTask

class MyTimerTask extends TimerTask  {
    JLabel currentDateTime;

     public MyTimerTask(JLabel aLabel) {
         this.currentDateTime = aLabel;
     }

     @Override
     public void run() {
         SwingUtilities.invokeLater(
                 new Runnable() {

                    public void run() {
                        // You can do anything you want with 'aLabel'
                         DateFormat dateandtime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                         Date date = new Date();
                         currentDateTime.setText(dateandtime.format(date));

                    }
                });
     }
}

Then, you need to create a java.util.Timer in startup of your application or UI. For example your main() method.

...

Timer timer = new Timer();
timer.schedule(new MyTimerTask(label), 0, 1000);

...

This is incorrectly synchronized; it accesses the JLabel from the timer's thread.

@MKAftab The comment by trashgod is correct; this example code is dangerously incorrect. Manipulating Swing components on a background thread will cause strange behavior and likely fail. Learn how to handle concurrency in Swing properly. Either revamp this code or withdraw the answer.

@Basil Your are correct. I edited my answer. Now every things goes through EDT. But now, I thinks, using Swing-Timer is a more convenient solution.

Looks good. Now replace the use of java.util.Date and SimpleDateFormat with Joda-Time and it would be perfect. ;-)

swing - Java timer, update every second - Stack Overflow

java swing date time timer
Rectangle 27 6

import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;

/** @see https://stackoverflow.com/a/11058263/230513 */
public class Clock {

    private Timer timer = new Timer();
    private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);

    public Clock() {
        JFrame f = new JFrame("Seconds");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(timeLabel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        timer.schedule(new UpdateUITask(), 0, 1000);
    }

    private class UpdateUITask extends TimerTask {

        int nSeconds = 0;

        @Override
        public void run() {
            EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    timeLabel.setText(String.valueOf(nSeconds++));
                }
            });
        }
    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                final Clock clock = new Clock();
            }
        });
    }
}

The timeLabel will always display the number of seconds the timer has been running.

I made the GUI using the visual editor from netbeans, how can I reference a jlabel inside the GUI?

@trashgod which part needs an invokeLater?

@GETah The run() method of UpdateUITask, since a java.util.Timer will run it off the EDT.

(Also, a ScheduleExecutorService would probably the more modern equivalent to a java.util.Timer to begin with, if only to use the same API anywhere you need to have background tasks running.)

swing - Java Stopwatch that updates the GUI every second? - Stack Over...

java swing user-interface stopwatch
Rectangle 27 5

First, build and display your GUI. Once the GUI is displayed, use a javax.swing.Timer to update the GUI every 500 millis:

final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
    private Iterator<Word> it = words.iterator();
    @Override 
    public void actionPerformed(ActionEvent e) {
        if (it.hasNext()) {
            label.setText(it.next().getName());
        }
        else {
            timer.stop();
        }
    }
};
timer.addActionListener(listener);
timer.start();

Concurency in Swing +1

I am going crazy over this. I just don't get how to get the timer to update the text. I can do it no problem with a String Array, but for some reason, when I try to read in a file, all breaks...

The GUI code should not read the file directly. Read the whole file in memory, store its content in a list in memory, and use the above code (unless of course the file is really too large to fit in memory).

public class TText{
Declare VARS;
SHOW GUI{}
GET TEXT IN{}
PRINT TEXT OUT{}
ACTIONLISTENER with TIMER updates GUI{}

swing - Update JLabel every X seconds from ArrayList - Java - St...

java swing concurrency timer freeze
Rectangle 27 5

First, build and display your GUI. Once the GUI is displayed, use a javax.swing.Timer to update the GUI every 500 millis:

final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
    private Iterator<Word> it = words.iterator();
    @Override 
    public void actionPerformed(ActionEvent e) {
        if (it.hasNext()) {
            label.setText(it.next().getName());
        }
        else {
            timer.stop();
        }
    }
};
timer.addActionListener(listener);
timer.start();

Concurency in Swing +1

I am going crazy over this. I just don't get how to get the timer to update the text. I can do it no problem with a String Array, but for some reason, when I try to read in a file, all breaks...

The GUI code should not read the file directly. Read the whole file in memory, store its content in a list in memory, and use the above code (unless of course the file is really too large to fit in memory).

public class TText{
Declare VARS;
SHOW GUI{}
GET TEXT IN{}
PRINT TEXT OUT{}
ACTIONLISTENER with TIMER updates GUI{}

swing - Update JLabel every X seconds from ArrayList - Java - St...

java swing concurrency timer freeze
Rectangle 27 1

A javax.swing.Timer is a little awkward for this; as is java.util.Timer. As long as you update your TableModel on the event dispatch thread, you can query the database on another thread every two seconds using either approach cited below. Note that it's OK to sleep on a background thread.

SwingWorker
Runnable

swing - Java JTable to be refreshed every 2 seconds - Stack Overflow

java swing timer jtable
Rectangle 27 6

If a key being pressed down is a trigger to update you GUI, that's when you need to incorperate SwingTimers. If it's not triggering an update to your GUI, you can just use normal threads.

  • Saving what keys are pressed using the KeyListener

Here's a sample of how you could incorporate that into your KeyListener:

public class Keyer implements KeyListener{

        /** Stores currently pressed keys */
        HashSet<Integer> pressedKeys = new HashSet<Integer>();

        public Keyer(){

            //Check every 100ms if there's keys pressed
            //(This is the Swing Timer they talk about)
            new Timer(100, new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    String keysString = "";
                    if(!pressedKeys.isEmpty()){
                        Iterator<Integer> i = pressedKeys.iterator();
                        while(i.hasNext()){
                            keysString += i.next() + ",";
                        }
                    } 
                    System.out.println(keysString);
                }
            }).start();
        }

        @Override
        public void keyPressed(KeyEvent ovent){
            //Add key to hashSet when pressed
            int keyCode = ovent.getKeyCode();
            pressedKeys.add(keyCode);
        }
        @Override
        public void keyReleased(KeyEvent ovent){
            //Remove key from hashset when released
            int keyCode = ovent.getKeyCode();
            pressedKeys.remove(keyCode);
        }
        @Override
        public void keyTyped(KeyEvent ovent){}
    }

Here's a sample where everything is put together - a label is updated telling you exactly what keys are pressed (by keycode).

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class TempProject extends JPanel{
    /** Label to update with currently pressed keys */
    JLabel output = new JLabel();

    public TempProject(){
        super();
        setFocusable(true);
        add(output, BorderLayout.CENTER);
        requestFocus();
        addKeyListener(new Keyer());
    }

    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                frame.setContentPane(new TempProject());    
                frame.pack();
                frame.setVisible(true);
                new TempProject();
            }
        });
    }

    public class Keyer implements KeyListener{

        /** Stores currently pressed keys */
        HashSet<Integer> pressedKeys = new HashSet<Integer>();

        public Keyer(){

            //Check every 100ms if there's keys pressed
            //(This is the Swing Timer they talk about)
            new Timer(100, new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    String keysString = "";
                    if(!pressedKeys.isEmpty()){
                        Iterator<Integer> i = pressedKeys.iterator();
                        while(i.hasNext()){
                            keysString += i.next() + ",";
                        }
                    } 
                    output.setText(keysString);
                }
            }).start();
        }

        @Override
        public void keyPressed(KeyEvent ovent){
            //Add key to hashSet when pressed
            int keyCode = ovent.getKeyCode();
            pressedKeys.add(keyCode);
        }
        @Override
        public void keyReleased(KeyEvent ovent){
            //Remove key from hashset when released
            int keyCode = ovent.getKeyCode();
            pressedKeys.remove(keyCode);
        }
        @Override
        public void keyTyped(KeyEvent ovent){}
    }



}

Also, please see warnings posted by @HovercraftFullOfEels about KeyListener. Depending on what you're trying to accomplish, you may want to look into using Key Bindings (same principle as this post applies). Here's a useful tutorial on Key Bindings if you'd like to take a look.

Why KeyListener and not Key Bindings? What happens when you add focusable components to the GUI? Are you going to prevent all components from getting focus for the KeyListener to work? If you do, that's a brittle kludge. A general rule for Swing GUI's is that use of KeyListeners should be avoided. Don't just believe my word on this, but also check out any posts by Jeanette/kleopatra and rob/camickr, two of the strongest Swing programmers I know, on this subject.

@HovercraftFullOfEels the question was about KeyListener, so that's what I answered it with. The same principle would apply to Key Bindings (registering when pressed/released). I understand the implications of using one over the other - But there also may be a reason for the OP to use a KeyListener.

Given his responses to my answer, it's safe to assume that he didn't even know about Key Bindings prior to asking this question, so I think that the chances are very low that there may be undisclosed reasons for his using a KeyListener. I think that we do him a disservice to give him code solutions that he shouldn't emulate.

talking about question on meta not about answers here :-) Actually with this thread, I'm undecided - the (assumed) context of the OP might be well inside the odd-use case which really requires a keyListener (bindings couldn't easily handle forced re-fires of keyEvents)

swing - Java KeyListener is Delayed Registration - Stack Overflow

java swing timer delay keylistener
Rectangle 27 5

If you're calling sleep() on the event handling thread, then yes, your GUI will freeze during that time. A better idea is to use a SwingTimer which will allow you to trigger playing of the second video after a specified delay without calling sleep().

Still could not make it working. It freeze as soon as its used inside Thread or Runnable or SwingTimer's...

Well, I answered before you showed the original code, remember. I assumed you already were playing the movie on the event thread, and that was the problem. But it turned out you weren't even creating a GUI, so obviously that's not it at all. Based on your comments about the proprietary player class, I think the only thing you can do is complain to the vendor, or go through their support or forums. This is obviously a bug or issue with that player library; it has nothing to do with any general Java programming issues.

swing - Is there any better or alternative way to skip/avoid using Thr...

java swing timer
Rectangle 27 2

Updating the view at 1 kHz is unrealistic; instead, consider the alternatives cited here. See this AnimationTest for an example of self-timing to determine your animation budget.

while(true)
System.currentTimeMillis()

Absent a Minimal, Complete, Tested and Readable Example, it's hard to say. You appear to be overriding paint(); was noted in Painting in AWT and Swing: The Paint Methods, "Swing programs should override paintComponent()." Moreover, you need to invoke super.paintComponent(), as shown here, to avoid visual artifacts.

I'm not sure where you got the 1 Hz. My Timer, which is set to refresh every 1 millisecond, is at 1,000 Hz (which is why I am not using it. I'm sorry that I didn't comment out the timer.start()). The while(true) loop at the top is running at 100 Hz. I actually modified it to refresh every 50/3 milliseconds, which lowers it to 60 Hz (The speed of my monitor), but still no success. Your answers were very useful, however! I appreciate it.

Wow! Thank you very much! When I printed out the time differences, they would always fluctuate by a few milliseconds. When the wait time went below 10 milliseconds, the screen flashed. I now know what to do to fix it. Thanks again!

i am reopening this question because I was not able to fix it. Any more help?

Please edit your question to include a Minimal, Complete, Tested and Readable Example that focuses on the problem.

swing - Java Graphics image refresh rate - Stack Overflow

java swing timer
Rectangle 27 2

Updating the view at 1 kHz is unrealistic; instead, consider the alternatives cited here. See this AnimationTest for an example of self-timing to determine your animation budget.

while(true)
System.currentTimeMillis()

Absent a Minimal, Complete, Tested and Readable Example, it's hard to say. You appear to be overriding paint(); was noted in Painting in AWT and Swing: The Paint Methods, "Swing programs should override paintComponent()." Moreover, you need to invoke super.paintComponent(), as shown here, to avoid visual artifacts.

I'm not sure where you got the 1 Hz. My Timer, which is set to refresh every 1 millisecond, is at 1,000 Hz (which is why I am not using it. I'm sorry that I didn't comment out the timer.start()). The while(true) loop at the top is running at 100 Hz. I actually modified it to refresh every 50/3 milliseconds, which lowers it to 60 Hz (The speed of my monitor), but still no success. Your answers were very useful, however! I appreciate it.

Wow! Thank you very much! When I printed out the time differences, they would always fluctuate by a few milliseconds. When the wait time went below 10 milliseconds, the screen flashed. I now know what to do to fix it. Thanks again!

i am reopening this question because I was not able to fix it. Any more help?

Please edit your question to include a Minimal, Complete, Tested and Readable Example that focuses on the problem.

swing - Java Graphics image refresh rate - Stack Overflow

java swing timer
Rectangle 27 5

I don't know what you want to do, but you pass this as argument to the Timer constructor. This means that every 2 seconds, the actionPerformed method of this (instance of ConcentrationGame4) will be called. And the first thing that this method does is

GameButton button = (GameButton) e.getSource();

Obviously, this will throw an exception, since the origin of the event won't be a game button, but the timer.

To understand what a Timer does and how it works, it's very simple. You just have to read its api doc : http://download.oracle.com/javase/6/docs/api/javax/swing/Timer.html. This doc will even lead you to a tutorial explaining how they work, with examples.

i just thought that if i use timer.start() on below the falsePair() method it will stop for 2 seconds and after it, it will continue to its work

No, that's not what a Timer does. Read the f** documentation. Thread.sleep does that, but if you do it in the event dispatch thread, the GUI will freeze for 2 seconds.

well ok i admitted this is so stupid post so i am going to delete it. sorry for making you angry : )

You didn't make me angry. Half of the questions I answer here could be answered by just reading the documentation. I just hope you learnt something, and that you'll now take the habit of reading the doc.

Don't delete this post or thread as it is not stupid in the least. And here I disagree with JB Nizet in that a Swing Timer will work for this, and in fact I've coded just such a thing. Just make it non-repeating.

java - swing timer doesn't work properly - Stack Overflow

java swing user-interface timer
Rectangle 27 6

An example of using a Swing Timer to pause action for xxx seconds:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class QuickTimerEg extends JPanel {
   private static final int TIMER_DELAY = 2000;
   private boolean buttonsWorking = true;
   private JButton btn1 = null;
   private JButton btn2 = null;
   private Timer swingTimer;

   public QuickTimerEg() {
      ActionListener btnListener = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            btnActionPerformed(e);
         }
      };
      setLayout(new GridLayout(4, 4));
      for (int i = 0; i < 4; i++) {
         for (int j = 0; j < 4; j++) {
            JButton button = new JButton("   ");
            button.addActionListener(btnListener);
            add(button);
         }
      }
   }

   private void btnActionPerformed(ActionEvent e) {
      if (!buttonsWorking) {
         return;
      }
      JButton button = (JButton)e.getSource();
      button.setBackground(Color.blue);
      button.setEnabled(false);
      if (btn1 == null) {
         btn1 = button;
      } else {
         buttonsWorking = false;
         btn2 = button;
         swingTimer = new Timer(TIMER_DELAY, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               btn1.setBackground(null);
               btn2.setBackground(null);
               btn1.setEnabled(true);
               btn2.setEnabled(true);
               btn1 = null;
               btn2 = null;
               buttonsWorking = true;               
            }
         });
         swingTimer.setRepeats(false);
         swingTimer.start();
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("QuickTimerEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new QuickTimerEg());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

i noticed that i must completely try to understand actionevents, cause i didnt know that we can use an actionlistener in an actionPerformed. so the thing is when an event is fired an actionlistener for that will handle with it, so what about the inner actionlistener. is it handles with the same event_? (and thanks a lot for helping cause i was stucked for days about this thing now it look more clear to understand)

so simple like as Swing is +1

java - swing timer doesn't work properly - Stack Overflow

java swing user-interface timer
Rectangle 27 4

Thats a bit over-complicated. Instead of using seconds, minutes, hours, you could just use java.util.Date, and java.text.SimpleDateFormat for displaying the time passed.

start = new Date(); // time right now
sdf = new SimpleDateFormat("hh:mm:ss");
Date now = new Date();
sdf.format(new Date(now.getTime() - start.getTime()); //create a date based on time passed

This will have the same effect and be much clearer and more consise.

swing - Creating a Count Up timer to Break in java - Stack Overflow

java swing timer jpanel jlabel
Rectangle 27 4

import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Random;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.table.*;

public class TableWithTimer implements ActionListener, Runnable {

    private static final long serialVersionUID = 1L;
    private JFrame frame = new JFrame();
    private JScrollPane scroll = new JScrollPane();
    private JTable myTable;
    private JPanel buttonPanel = new JPanel();
    private JButton startButton = new JButton("Start Thread to Update Table");
    private JButton stopButton = new JButton("Stop Thread for Update Table");
    private JButton newButton = new JButton("Load new Data to Table");
    private int count = 0;
    private int delay = 3;
    private javax.swing.Timer timer = null;
    private boolean runProcess;
    private int row = 0;
    private int column = 0;
    private String value = "Amnd";
    private int amndValue = 0;
    private String valueAt = "";
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    private String[] head = {"One", "Two", "Three", "Four", "Five", "Six"};
    private String[][] data = new String[25][6];

    public TableWithTimer() {
        myTable = new TableBackroundPaint0(data, head);
        myTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        myTable.setGridColor(Color.gray);
        myTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        final TableCellRenderer cellRendener = myTable.getTableHeader().getDefaultRenderer();
        myTable.getTableHeader().setDefaultRenderer(new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel label = (JLabel) cellRendener.getTableCellRendererComponent(
                        table, value, isSelected, hasFocus, row, column);
                label.setBackground(Color.orange);
                label.setForeground(Color.darkGray);
                label.setFont(new Font("SansSerif", Font.BOLD, 12));
                label.setBorder(BorderFactory.createCompoundBorder(label.getBorder(),
                        BorderFactory.createEmptyBorder(0, 5, 0, 0)));
                label.setHorizontalAlignment(SwingConstants.LEFT);
                label.setHorizontalAlignment(SwingConstants.CENTER);
                if ((label.getText().equals("First")) || (label.getText().equals("Second"))) {
                    label.setForeground(Color.red);
                }
                if ((label.getText().equals("Day")) || (label.getText().equals("Month")) || (label.getText().equals("Year"))) {
                    label.setForeground(Color.blue);
                }
                if ((label.getText().equals("Time"))) {
                    label.setForeground(Color.green);
                }
                return label;
            }
        });
        TableColumnModel cm = myTable.getColumnModel();
        for (int column1 = 0; column1 < cm.getColumnCount(); column1++) {
            TableColumn colLeft1 = cm.getColumn(column1);
            cm.getColumn(column1).setWidth(140);
            cm.getColumn(column1).setPreferredWidth(140);
        }
        //myTable.setFillsViewportHeight(true); // apply paintComponent for whole Viewport
        JButton cornerButtonTop = new JButton();
        cornerButtonTop.setBackground(scroll.getViewport().getBackground());
        JButton cornerButtonBottom = new JButton();
        cornerButtonBottom.setOpaque(false);
        scroll.setCorner(JScrollPane.UPPER_RIGHT_CORNER, cornerButtonTop);
        scroll.setCorner(JScrollPane.LOWER_RIGHT_CORNER, cornerButtonBottom);
        scroll.setViewportView(myTable);
        scroll.setMinimumSize(new Dimension(600, 400));
        scroll.setMaximumSize(new Dimension(900, 600));
        scroll.setPreferredSize(new Dimension(850, 430));
        frame.add(scroll, BorderLayout.CENTER);
        buttonPanel.setLayout(new GridLayout(1, 4, 10, 10));
        startButton.addActionListener(this);
        startButton.setEnabled(false);
        stopButton.addActionListener(this);
        stopButton.setEnabled(false);
        JButton hideButton = new JButton();
        newButton.addActionListener(this);
        newButton.setEnabled(false);
        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);
        buttonPanel.add(hideButton);
        buttonPanel.add(newButton);
        hideButton.setVisible(false);
        frame.add(buttonPanel, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);
        start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == startButton) {
            runProcess = true;
            new Thread(this).start();
            myTable.requestFocus();
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
        } else if (e.getSource() == stopButton) {
            scroll.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            runProcess = false;
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            newButton.setEnabled(true);
        } else if (e.getSource() == newButton) {
            runProcess = false;
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            newButton.setEnabled(false);
            addNewData();
        }
    }

    public void addNewData() {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableModel model = myTable.getModel();
                for (int j = 0; j < model.getRowCount(); j++) {
                    int column = model.getColumnCount();
                    for (int i = 0; i < column; i++) {
                        model.setValueAt("Deleted", j, i);
                    }
                }
                startNewData();
            }
        });
    }

    private void start() {
        scroll.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        timer = new javax.swing.Timer(delay * 100, updateCol());
        timer.start();
    }

    private void startNewData() {
        scroll.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        count = 0;
        timer = new javax.swing.Timer(1500, updateCol());
        timer.start();
    }

    @Override
    public void run() {
        scroll.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        count = 0;
        Random random = new Random();
        while (runProcess) {
            row = random.nextInt(myTable.getRowCount());
            column = random.nextInt(myTable.getColumnCount());
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    try {
                        amndValue++;
                        valueAt = ((myTable.getValueAt(row, column)).toString());
                        if (!(valueAt.startsWith("A"))) {
                            count++;
                            if (count == ((25 * 6))) {
                                JOptionPane.showMessageDialog(myTable, " Update done ");
                                scroll.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                                runProcess = false;
                            }
                            java.util.Date date = new java.util.Date();
                            String dateTime = sdf.format(date.getTime());
                            myTable.setValueAt((value + " " + String.valueOf(amndValue) + " at: " + dateTime), row, column);
                            //myTable.setValueAt(new Integer(1), row, column); // please uncoment for generate misstype error on EDT
                            myTable.changeSelection(row, column, false, false);
                            System.out.println("update cycle with value :"
                                    + (value + " " + String.valueOf(amndValue) + " at: " + dateTime) + ", table row :" + row
                                    + ", table column " + column);
                        }
                    } catch (Exception e) {
                        runProcess = false;
                        System.out.println("Error for update JTable cell");
                        e.printStackTrace();
                    }
                }
            });
            try {
                Thread.sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Action updateCol() {
        return new AbstractAction("text load action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {

                System.out.println("updating row " + (count + 1));
                TableModel model = myTable.getModel();
                int cols = model.getColumnCount();
                int row = 0;
                for (int j = 0; j < cols; j++) {
                    row = count;
                    myTable.changeSelection(row, 0, false, false);
                    timer.setDelay(200);
                    Object value = "row " + (count + 1) + " item " + (j + 1);
                    model.setValueAt(value, count, j);
                }
                count++;
                if (count >= myTable.getRowCount()) {
                    myTable.changeSelection(0, 0, false, false);
                    timer.stop();
                    System.out.println("update cycle completed");
                    myTable.clearSelection();
                    startButton.setEnabled(true);
                    newButton.setEnabled(true);
                    scroll.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                }
            }
        };
    }

    public static void main(String args[]) {
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                System.out.println(info.getName());
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        }
        TableWithTimer tableWithTimer = new TableWithTimer();
    }
}

class TableBackroundPaint0 extends JTable {

    private static final long serialVersionUID = 1L;

    TableBackroundPaint0(Object[][] data, Object[] head) {
        super(data, head);
        setOpaque(false);
        ((JComponent) getDefaultRenderer(Object.class)).setOpaque(false);
    }

    @Override
    public void paintComponent(Graphics g) {
        Color background = new Color(168, 210, 241);
        Color controlColor = new Color(230, 240, 230);
        int width = getWidth();
        int height = getHeight();
        Graphics2D g2 = (Graphics2D) g;
        Paint oldPaint = g2.getPaint();
        g2.setPaint(new GradientPaint(0, 0, background, width, 0, controlColor));
        g2.fillRect(0, 0, width, height);
        g2.setPaint(oldPaint);
        for (int row : getSelectedRows()) {
            Rectangle start = getCellRect(row, 0, true);
            Rectangle end = getCellRect(row, getColumnCount() - 1, true);
            g2.setPaint(new GradientPaint(start.x, 0, controlColor, (int) ((end.x + end.width - start.x) * 1.25), 0, Color.orange));
            g2.fillRect(start.x, start.y, end.x + end.width - start.x, start.height);
        }
        super.paintComponent(g);
    }
}

+1 for javax.swing.Timer; the gradient is fun, too.

@trashgod this gradient is a work of art, for the viewport and SelectedRow(s) too, Nimbus is very coldColored, but this stackoverflow.com/questions/1249278/ look very well in Nimbus L&F,

swing - java wait cursor display problem - Stack Overflow

java swing busy-cursor
Rectangle 27 1

In all likelihood, this isn't a software issue, nor is it fixable with software. Your screen probably only refreshes about 60 times a second, meaning that the frames are only drawn 60 times per second, or once every (approximately) 16 milliseconds. Since this is a hardware barrier, there's no way to get it to update faster with software. You can probably count on your users only having 60Hz monitors, too, so it's more worthwhile to look into other solutions.

One solution that pops to mind is adding in motion blur, to make it seem like the ships are moving faster when they really aren't. It'll allow you to 'jump' a greater distance before it looks jumpy, since the blur tricks the eye into thinking it's going really fast instead of hopping across the screen. Unfortunately, the only things that I see to do motion blur are third-party libraries, though you may have better luck Googling.

While the refresh rate (and delay) ultimately affects the user experience, the Swing Timer is independent of the monitor refresh rate.

@user2864740 That's interesting. Nonetheless, what I said is still true, and given that both are around the same time, it's a tossup as to which it actually is.

Java 2D Game Performance with Java Swing Timer - Stack Overflow

java swing timer graphics2d
Rectangle 27 6

Never use Thread.sleep(int) inside Swing Code, because it blocks the EDT; more here,

The result of using Thread.sleep(int) is this:

Thread.sleep(int)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private Queue<Icon> iconQueue = new LinkedList<Icon>();
    private JLabel label = new JLabel();
    private Random random = new Random();
    private JPanel buttonPanel = new JPanel();
    private JPanel labelPanel = new JPanel();
    private Timer backTtimer;
    private Timer labelTimer;
    private JLabel one = new JLabel("one");
    private JLabel two = new JLabel("two");
    private JLabel three = new JLabel("three");
    private final String[] petStrings = {"Bird", "Cat", "Dog",
        "Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
    private boolean runProcess = true;
    private int index = 1;
    private int index1 = 1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ButtonsIcon t = new ButtonsIcon();
            }
        });
    }

    public ButtonsIcon() {
        iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));

        one.setFont(new Font("Dialog", Font.BOLD, 24));
        one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        two.setFont(new Font("Dialog", Font.BOLD, 24));
        two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        three.setFont(new Font("Dialog", Font.BOLD, 10));
        three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelPanel.setLayout(new GridLayout(0, 3, 4, 4));

        labelPanel.add(one);
        labelPanel.add(two);
        labelPanel.add(three);
        //labelPanel.setBorder(new LineBorder(Color.black, 1));
        labelPanel.setOpaque(false);

        JButton button0 = createButton();
        JButton button1 = createButton();
        JButton button2 = createButton();
        JButton button3 = createButton();

        buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
        buttonPanel.add(button0);
        buttonPanel.add(button1);
        buttonPanel.add(button2);
        buttonPanel.add(button3);
        //buttonPanel.setBorder(new LineBorder(Color.black, 1));
        buttonPanel.setOpaque(false);

        label.setLayout(new BorderLayout());
        label.add(labelPanel, BorderLayout.NORTH);
        label.add(buttonPanel, BorderLayout.SOUTH);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));

        add(label, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
        startBackground();
        startLabel2();
        new Thread(this).start();
        printWords(); // generating freeze Swing GUI durring EDT
    }

    private JButton createButton() {
        JButton button = new JButton();
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setFocusable(false);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setContentAreaFilled(false);
        button.setIcon(nextIcon());
        button.setRolloverIcon(nextIcon());
        button.setPressedIcon(nextIcon());
        button.setDisabledIcon(nextIcon());
        nextIcon();
        return button;
    }

    private Icon nextIcon() {
        Icon icon = iconQueue.peek();
        iconQueue.add(iconQueue.remove());
        return icon;
    }

    // Update background at 4/3 Hz
    private void startBackground() {
        backTtimer = new javax.swing.Timer(750, updateBackground());
        backTtimer.start();
        backTtimer.setRepeats(true);
    }

    private Action updateBackground() {
        return new AbstractAction("Background action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setIcon(new ImageIcon(getImage()));
            }
        };
    }

    // Update Label two at 2 Hz
    private void startLabel2() {
        labelTimer = new javax.swing.Timer(500, updateLabel2());
        labelTimer.start();
        labelTimer.setRepeats(true);
    }

    private Action updateLabel2() {
        return new AbstractAction("Label action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                two.setText(petStrings[index]);
                index = (index + 1) % petStrings.length;
            }
        };
    }

    // Update lable one at 3 Hz
    @Override
    public void run() {
        while (runProcess) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    one.setText(petStrings[index1]);
                    index1 = (index1 + 1) % petStrings.length;
                }
            });
            try {
                Thread.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // Note: blocks EDT
    private void printWords() {
        for (int i = 0; i < petStrings.length; i++) {
            String word = petStrings[i].toString();
            System.out.println(word);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            three.setText(word);
        }
        three.setText("<html> Concurency Issues in Swing<br>"
                + " never to use Thread.sleep(int) <br>"
                + " durring EDT, simple to freeze GUI </html>");
    }

    public BufferedImage getImage() {
        int w = label.getWidth();
        int h = label.getHeight();
        GradientPaint gp = new GradientPaint(0f, 0f, new Color(
                127 + random.nextInt(128),
                127 + random.nextInt(128),
                127 + random.nextInt(128)),
                w, w,
                new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        g2d.setColor(Color.BLACK);
        return bi;
    }
}

@Andrew Thompson I share your great idea, but void convertToFromBytes work strange. isn't there another way how to converting Graphics2D to the plain Image File

+1 I took the liberty of refactoring your instructive example.

@trashgod thanks!, since I created this quickly codes example upto 10mins, your coding skills/dimensions still missed somwhere in my newbee mind, really I must start to learn How to wrote code (I cann't refuse wrong programing habits from RPG/Cobol)

@trashgod I tried your changes on full screen size(2x FullHd monitor), these things to protect the world against stupidity, again thank you

@mKorbel : Many new things for me to learn in this code, You really are too good in Swing :-)

swing - Update JLabel every X seconds from ArrayList - Java - St...

java swing concurrency timer freeze
Rectangle 27 6

Never use Thread.sleep(int) inside Swing Code, because it blocks the EDT; more here,

The result of using Thread.sleep(int) is this:

Thread.sleep(int)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.*;
//http://stackoverflow.com/questions/7943584/update-jlabel-every-x-seconds-from-arraylistlist-java
public class ButtonsIcon extends JFrame implements Runnable {

    private static final long serialVersionUID = 1L;
    private Queue<Icon> iconQueue = new LinkedList<Icon>();
    private JLabel label = new JLabel();
    private Random random = new Random();
    private JPanel buttonPanel = new JPanel();
    private JPanel labelPanel = new JPanel();
    private Timer backTtimer;
    private Timer labelTimer;
    private JLabel one = new JLabel("one");
    private JLabel two = new JLabel("two");
    private JLabel three = new JLabel("three");
    private final String[] petStrings = {"Bird", "Cat", "Dog",
        "Rabbit", "Pig", "Fish", "Horse", "Cow", "Bee", "Skunk"};
    private boolean runProcess = true;
    private int index = 1;
    private int index1 = 1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ButtonsIcon t = new ButtonsIcon();
            }
        });
    }

    public ButtonsIcon() {
        iconQueue.add(UIManager.getIcon("OptionPane.errorIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.informationIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.warningIcon"));
        iconQueue.add(UIManager.getIcon("OptionPane.questionIcon"));

        one.setFont(new Font("Dialog", Font.BOLD, 24));
        one.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        two.setFont(new Font("Dialog", Font.BOLD, 24));
        two.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        three.setFont(new Font("Dialog", Font.BOLD, 10));
        three.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        labelPanel.setLayout(new GridLayout(0, 3, 4, 4));

        labelPanel.add(one);
        labelPanel.add(two);
        labelPanel.add(three);
        //labelPanel.setBorder(new LineBorder(Color.black, 1));
        labelPanel.setOpaque(false);

        JButton button0 = createButton();
        JButton button1 = createButton();
        JButton button2 = createButton();
        JButton button3 = createButton();

        buttonPanel.setLayout(new GridLayout(0, 4, 4, 4));
        buttonPanel.add(button0);
        buttonPanel.add(button1);
        buttonPanel.add(button2);
        buttonPanel.add(button3);
        //buttonPanel.setBorder(new LineBorder(Color.black, 1));
        buttonPanel.setOpaque(false);

        label.setLayout(new BorderLayout());
        label.add(labelPanel, BorderLayout.NORTH);
        label.add(buttonPanel, BorderLayout.SOUTH);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        label.setPreferredSize(new Dimension(d.width / 3, d.height / 3));

        add(label, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
        startBackground();
        startLabel2();
        new Thread(this).start();
        printWords(); // generating freeze Swing GUI durring EDT
    }

    private JButton createButton() {
        JButton button = new JButton();
        button.setBorderPainted(false);
        button.setBorder(null);
        button.setFocusable(false);
        button.setMargin(new Insets(0, 0, 0, 0));
        button.setContentAreaFilled(false);
        button.setIcon(nextIcon());
        button.setRolloverIcon(nextIcon());
        button.setPressedIcon(nextIcon());
        button.setDisabledIcon(nextIcon());
        nextIcon();
        return button;
    }

    private Icon nextIcon() {
        Icon icon = iconQueue.peek();
        iconQueue.add(iconQueue.remove());
        return icon;
    }

    // Update background at 4/3 Hz
    private void startBackground() {
        backTtimer = new javax.swing.Timer(750, updateBackground());
        backTtimer.start();
        backTtimer.setRepeats(true);
    }

    private Action updateBackground() {
        return new AbstractAction("Background action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                label.setIcon(new ImageIcon(getImage()));
            }
        };
    }

    // Update Label two at 2 Hz
    private void startLabel2() {
        labelTimer = new javax.swing.Timer(500, updateLabel2());
        labelTimer.start();
        labelTimer.setRepeats(true);
    }

    private Action updateLabel2() {
        return new AbstractAction("Label action") {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                two.setText(petStrings[index]);
                index = (index + 1) % petStrings.length;
            }
        };
    }

    // Update lable one at 3 Hz
    @Override
    public void run() {
        while (runProcess) {
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    one.setText(petStrings[index1]);
                    index1 = (index1 + 1) % petStrings.length;
                }
            });
            try {
                Thread.sleep(300);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // Note: blocks EDT
    private void printWords() {
        for (int i = 0; i < petStrings.length; i++) {
            String word = petStrings[i].toString();
            System.out.println(word);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            three.setText(word);
        }
        three.setText("<html> Concurency Issues in Swing<br>"
                + " never to use Thread.sleep(int) <br>"
                + " durring EDT, simple to freeze GUI </html>");
    }

    public BufferedImage getImage() {
        int w = label.getWidth();
        int h = label.getHeight();
        GradientPaint gp = new GradientPaint(0f, 0f, new Color(
                127 + random.nextInt(128),
                127 + random.nextInt(128),
                127 + random.nextInt(128)),
                w, w,
                new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bi.createGraphics();
        g2d.setPaint(gp);
        g2d.fillRect(0, 0, w, h);
        g2d.setColor(Color.BLACK);
        return bi;
    }
}

@Andrew Thompson I share your great idea, but void convertToFromBytes work strange. isn't there another way how to converting Graphics2D to the plain Image File

+1 I took the liberty of refactoring your instructive example.

@trashgod thanks!, since I created this quickly codes example upto 10mins, your coding skills/dimensions still missed somwhere in my newbee mind, really I must start to learn How to wrote code (I cann't refuse wrong programing habits from RPG/Cobol)

@trashgod I tried your changes on full screen size(2x FullHd monitor), these things to protect the world against stupidity, again thank you

@mKorbel : Many new things for me to learn in this code, You really are too good in Swing :-)

swing - Update JLabel every X seconds from ArrayList - Java - St...

java swing concurrency timer freeze
Rectangle 27 15

Your use of threading is all wrong for Swing applications. You should not be trying to add or remove components in a background thread but instead should use a Swing Timer to do this on the Swing event thread.

I want to have a scrolling JLabel at the bottom of the screen

I also understand that I will most likely not be able to use FlowLayout for this, as I understand it does not allow you to set the location of your components. I tried using null layout, but with null layout the empty JLabel with a border does not appear. I can barely make out the top of the border at the bottom edge of the frame, but even with setLocation I cannot get it to appear where I want it to.

No, don't use null layout for this situation. There are much better layout managers that can help you build your application in a cleaner more platform-independent manner.

I would create a JPanel for the bottom of the screen for the purposes of either holding your JLabel or displaying the image without a JLabel by overriding its paintComponent(...) method. If you use it as a container, then yes, its layout should be null, but the rest of the GUI should not be using null layout. The Swing Timer would simply change the JLabel's location and then call repaint() on its JPanel/container. If you go the latter route, you would draw the image in the JPanel's paintComponent(...) method using g.drawImage(myImage, x, y), and your timer would change x and/or y and call repaint() on the drawing JPanel.

Also, you likely do not want to keep adding a JLabel in your timer but rather simply moving the JLabel that's already displayed in the GUI.

Also, to avoid focus issues, don't use a KeyListener to capture keystroke input but rather use Key Bindings. Google will direct you to a great tutorial on this construct.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EnumMap;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class AnimateExample extends JPanel {
   public static final String DUKE_IMG_PATH = 
         "https://duke.kenai.com/iconSized/duke.gif";
   private static final int PREF_W = 800;
   private static final int PREF_H = 800;
   private static final int TIMER_DELAY = 20;
   private static final String KEY_DOWN = "key down";
   private static final String KEY_RELEASE = "key release";
   public static final int TRANSLATE_SCALE = 3;
   private static final String BACKGROUND_STRING = "Use Arrow Keys to Move Image";
   private static final Font BG_STRING_FONT = new Font(Font.SANS_SERIF,
         Font.BOLD, 32);
   private EnumMap<Direction, Boolean> dirMap = 
         new EnumMap<AnimateExample.Direction, Boolean>(Direction.class);
   private BufferedImage image = null;
   private int imgX = 0;
   private int imgY = 0;
   private int bgStringX; 
   private int bgStringY; 

   public AnimateExample() {
      for (Direction dir : Direction.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      try {
         URL imgUrl = new URL(DUKE_IMG_PATH);
         image = ImageIO.read(imgUrl);
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      new Timer(TIMER_DELAY, new TimerListener()).start();

      // here we set up our key bindings
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      for (final Direction dir : Direction.values()) {

         // for the key down key stroke
         KeyStroke keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0,
               false);
         inputMap.put(keyStroke, dir.name() + KEY_DOWN);
         actionMap.put(dir.name() + KEY_DOWN, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, true);
            }
         });

         // for the key release key stroke
         keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, true);
         inputMap.put(keyStroke, dir.name() + KEY_RELEASE);
         actionMap.put(dir.name() + KEY_RELEASE, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, false);
            }
         });
      }

      FontMetrics fontMetrics = getFontMetrics(BG_STRING_FONT);
      int w = fontMetrics.stringWidth(BACKGROUND_STRING);
      int h = fontMetrics.getHeight();

      bgStringX = (PREF_W - w) / 2;
      bgStringY = (PREF_H - h) / 2;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g.setFont(BG_STRING_FONT);
      g.setColor(Color.LIGHT_GRAY);
      g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      g.drawString(BACKGROUND_STRING, bgStringX, bgStringY);

      if (image != null) {
         g.drawImage(image, imgX, imgY, this);
      }
   }

   private class TimerListener implements ActionListener {
      public void actionPerformed(java.awt.event.ActionEvent e) {
         for (Direction dir : Direction.values()) {
            if (dirMap.get(dir)) {
               imgX += dir.getX() * TRANSLATE_SCALE;
               imgY += dir.getY() * TRANSLATE_SCALE;
            }
         }
         repaint();
      };
   }

   enum Direction {
      Up(KeyEvent.VK_UP, 0, -1), Down(KeyEvent.VK_DOWN, 0, 1), Left(
            KeyEvent.VK_LEFT, -1, 0), Right(KeyEvent.VK_RIGHT, 1, 0);

      private int keyCode;
      private int x;
      private int y;

      private Direction(int keyCode, int x, int y) {
         this.keyCode = keyCode;
         this.x = x;
         this.y = y;
      }

      public int getKeyCode() {
         return keyCode;
      }

      public int getX() {
         return x;
      }

      public int getY() {
         return y;
      }

   }

   private static void createAndShowGui() {
      AnimateExample mainPanel = new AnimateExample();

      JFrame frame = new JFrame("Animate Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

+1. And setting the location while using a LayoutManager has no effect . It is the LayoutManager which determines the location

I actually had the Timer before, but somebody told me it was better to use ScheduledExecutorService. Putting it back to using the Swing timer is no issue, I'll edit the question

If still not working, then create a simple compilable and runnable program that demonstrates your problem and that uses online images available to all, an sscce.

To clarify, at the bottom of the screen I want a JLabel at the far right corner, then in the swing timer, the JLabel will gradually move to the left until it leaves the screen. If I could get setLocation to work, the basic premise would be to have a variable x set to 600, and then every second decrement x by say 50 and then redraw the JLabel at the new location on the screen. Basic animation.

@awestover89: please see edit 3 and edit 4 for an example of what I'm talking about, both sscce-size and animation-wise.

swing - Java Animate JLabel - Stack Overflow

java swing animation timer awt
Rectangle 27 15

Your use of threading is all wrong for Swing applications. You should not be trying to add or remove components in a background thread but instead should use a Swing Timer to do this on the Swing event thread.

I want to have a scrolling JLabel at the bottom of the screen

I also understand that I will most likely not be able to use FlowLayout for this, as I understand it does not allow you to set the location of your components. I tried using null layout, but with null layout the empty JLabel with a border does not appear. I can barely make out the top of the border at the bottom edge of the frame, but even with setLocation I cannot get it to appear where I want it to.

No, don't use null layout for this situation. There are much better layout managers that can help you build your application in a cleaner more platform-independent manner.

I would create a JPanel for the bottom of the screen for the purposes of either holding your JLabel or displaying the image without a JLabel by overriding its paintComponent(...) method. If you use it as a container, then yes, its layout should be null, but the rest of the GUI should not be using null layout. The Swing Timer would simply change the JLabel's location and then call repaint() on its JPanel/container. If you go the latter route, you would draw the image in the JPanel's paintComponent(...) method using g.drawImage(myImage, x, y), and your timer would change x and/or y and call repaint() on the drawing JPanel.

Also, you likely do not want to keep adding a JLabel in your timer but rather simply moving the JLabel that's already displayed in the GUI.

Also, to avoid focus issues, don't use a KeyListener to capture keystroke input but rather use Key Bindings. Google will direct you to a great tutorial on this construct.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EnumMap;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class AnimateExample extends JPanel {
   public static final String DUKE_IMG_PATH = 
         "https://duke.kenai.com/iconSized/duke.gif";
   private static final int PREF_W = 800;
   private static final int PREF_H = 800;
   private static final int TIMER_DELAY = 20;
   private static final String KEY_DOWN = "key down";
   private static final String KEY_RELEASE = "key release";
   public static final int TRANSLATE_SCALE = 3;
   private static final String BACKGROUND_STRING = "Use Arrow Keys to Move Image";
   private static final Font BG_STRING_FONT = new Font(Font.SANS_SERIF,
         Font.BOLD, 32);
   private EnumMap<Direction, Boolean> dirMap = 
         new EnumMap<AnimateExample.Direction, Boolean>(Direction.class);
   private BufferedImage image = null;
   private int imgX = 0;
   private int imgY = 0;
   private int bgStringX; 
   private int bgStringY; 

   public AnimateExample() {
      for (Direction dir : Direction.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      try {
         URL imgUrl = new URL(DUKE_IMG_PATH);
         image = ImageIO.read(imgUrl);
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      new Timer(TIMER_DELAY, new TimerListener()).start();

      // here we set up our key bindings
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      for (final Direction dir : Direction.values()) {

         // for the key down key stroke
         KeyStroke keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0,
               false);
         inputMap.put(keyStroke, dir.name() + KEY_DOWN);
         actionMap.put(dir.name() + KEY_DOWN, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, true);
            }
         });

         // for the key release key stroke
         keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, true);
         inputMap.put(keyStroke, dir.name() + KEY_RELEASE);
         actionMap.put(dir.name() + KEY_RELEASE, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, false);
            }
         });
      }

      FontMetrics fontMetrics = getFontMetrics(BG_STRING_FONT);
      int w = fontMetrics.stringWidth(BACKGROUND_STRING);
      int h = fontMetrics.getHeight();

      bgStringX = (PREF_W - w) / 2;
      bgStringY = (PREF_H - h) / 2;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g.setFont(BG_STRING_FONT);
      g.setColor(Color.LIGHT_GRAY);
      g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      g.drawString(BACKGROUND_STRING, bgStringX, bgStringY);

      if (image != null) {
         g.drawImage(image, imgX, imgY, this);
      }
   }

   private class TimerListener implements ActionListener {
      public void actionPerformed(java.awt.event.ActionEvent e) {
         for (Direction dir : Direction.values()) {
            if (dirMap.get(dir)) {
               imgX += dir.getX() * TRANSLATE_SCALE;
               imgY += dir.getY() * TRANSLATE_SCALE;
            }
         }
         repaint();
      };
   }

   enum Direction {
      Up(KeyEvent.VK_UP, 0, -1), Down(KeyEvent.VK_DOWN, 0, 1), Left(
            KeyEvent.VK_LEFT, -1, 0), Right(KeyEvent.VK_RIGHT, 1, 0);

      private int keyCode;
      private int x;
      private int y;

      private Direction(int keyCode, int x, int y) {
         this.keyCode = keyCode;
         this.x = x;
         this.y = y;
      }

      public int getKeyCode() {
         return keyCode;
      }

      public int getX() {
         return x;
      }

      public int getY() {
         return y;
      }

   }

   private static void createAndShowGui() {
      AnimateExample mainPanel = new AnimateExample();

      JFrame frame = new JFrame("Animate Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

+1. And setting the location while using a LayoutManager has no effect . It is the LayoutManager which determines the location

I actually had the Timer before, but somebody told me it was better to use ScheduledExecutorService. Putting it back to using the Swing timer is no issue, I'll edit the question

If still not working, then create a simple compilable and runnable program that demonstrates your problem and that uses online images available to all, an sscce.

To clarify, at the bottom of the screen I want a JLabel at the far right corner, then in the swing timer, the JLabel will gradually move to the left until it leaves the screen. If I could get setLocation to work, the basic premise would be to have a variable x set to 600, and then every second decrement x by say 50 and then redraw the JLabel at the new location on the screen. Basic animation.

@awestover89: please see edit 3 and edit 4 for an example of what I'm talking about, both sscce-size and animation-wise.

swing - Java Animate JLabel - Stack Overflow

java swing animation timer awt
Rectangle 27 15

Your use of threading is all wrong for Swing applications. You should not be trying to add or remove components in a background thread but instead should use a Swing Timer to do this on the Swing event thread.

I want to have a scrolling JLabel at the bottom of the screen

I also understand that I will most likely not be able to use FlowLayout for this, as I understand it does not allow you to set the location of your components. I tried using null layout, but with null layout the empty JLabel with a border does not appear. I can barely make out the top of the border at the bottom edge of the frame, but even with setLocation I cannot get it to appear where I want it to.

No, don't use null layout for this situation. There are much better layout managers that can help you build your application in a cleaner more platform-independent manner.

I would create a JPanel for the bottom of the screen for the purposes of either holding your JLabel or displaying the image without a JLabel by overriding its paintComponent(...) method. If you use it as a container, then yes, its layout should be null, but the rest of the GUI should not be using null layout. The Swing Timer would simply change the JLabel's location and then call repaint() on its JPanel/container. If you go the latter route, you would draw the image in the JPanel's paintComponent(...) method using g.drawImage(myImage, x, y), and your timer would change x and/or y and call repaint() on the drawing JPanel.

Also, you likely do not want to keep adding a JLabel in your timer but rather simply moving the JLabel that's already displayed in the GUI.

Also, to avoid focus issues, don't use a KeyListener to capture keystroke input but rather use Key Bindings. Google will direct you to a great tutorial on this construct.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EnumMap;

import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class AnimateExample extends JPanel {
   public static final String DUKE_IMG_PATH = 
         "https://duke.kenai.com/iconSized/duke.gif";
   private static final int PREF_W = 800;
   private static final int PREF_H = 800;
   private static final int TIMER_DELAY = 20;
   private static final String KEY_DOWN = "key down";
   private static final String KEY_RELEASE = "key release";
   public static final int TRANSLATE_SCALE = 3;
   private static final String BACKGROUND_STRING = "Use Arrow Keys to Move Image";
   private static final Font BG_STRING_FONT = new Font(Font.SANS_SERIF,
         Font.BOLD, 32);
   private EnumMap<Direction, Boolean> dirMap = 
         new EnumMap<AnimateExample.Direction, Boolean>(Direction.class);
   private BufferedImage image = null;
   private int imgX = 0;
   private int imgY = 0;
   private int bgStringX; 
   private int bgStringY; 

   public AnimateExample() {
      for (Direction dir : Direction.values()) {
         dirMap.put(dir, Boolean.FALSE);
      }
      try {
         URL imgUrl = new URL(DUKE_IMG_PATH);
         image = ImageIO.read(imgUrl);
      } catch (MalformedURLException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }

      new Timer(TIMER_DELAY, new TimerListener()).start();

      // here we set up our key bindings
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      for (final Direction dir : Direction.values()) {

         // for the key down key stroke
         KeyStroke keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0,
               false);
         inputMap.put(keyStroke, dir.name() + KEY_DOWN);
         actionMap.put(dir.name() + KEY_DOWN, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, true);
            }
         });

         // for the key release key stroke
         keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, true);
         inputMap.put(keyStroke, dir.name() + KEY_RELEASE);
         actionMap.put(dir.name() + KEY_RELEASE, new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
               dirMap.put(dir, false);
            }
         });
      }

      FontMetrics fontMetrics = getFontMetrics(BG_STRING_FONT);
      int w = fontMetrics.stringWidth(BACKGROUND_STRING);
      int h = fontMetrics.getHeight();

      bgStringX = (PREF_W - w) / 2;
      bgStringY = (PREF_H - h) / 2;
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g;
      g.setFont(BG_STRING_FONT);
      g.setColor(Color.LIGHT_GRAY);
      g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
            RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      g.drawString(BACKGROUND_STRING, bgStringX, bgStringY);

      if (image != null) {
         g.drawImage(image, imgX, imgY, this);
      }
   }

   private class TimerListener implements ActionListener {
      public void actionPerformed(java.awt.event.ActionEvent e) {
         for (Direction dir : Direction.values()) {
            if (dirMap.get(dir)) {
               imgX += dir.getX() * TRANSLATE_SCALE;
               imgY += dir.getY() * TRANSLATE_SCALE;
            }
         }
         repaint();
      };
   }

   enum Direction {
      Up(KeyEvent.VK_UP, 0, -1), Down(KeyEvent.VK_DOWN, 0, 1), Left(
            KeyEvent.VK_LEFT, -1, 0), Right(KeyEvent.VK_RIGHT, 1, 0);

      private int keyCode;
      private int x;
      private int y;

      private Direction(int keyCode, int x, int y) {
         this.keyCode = keyCode;
         this.x = x;
         this.y = y;
      }

      public int getKeyCode() {
         return keyCode;
      }

      public int getX() {
         return x;
      }

      public int getY() {
         return y;
      }

   }

   private static void createAndShowGui() {
      AnimateExample mainPanel = new AnimateExample();

      JFrame frame = new JFrame("Animate Example");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

+1. And setting the location while using a LayoutManager has no effect . It is the LayoutManager which determines the location

I actually had the Timer before, but somebody told me it was better to use ScheduledExecutorService. Putting it back to using the Swing timer is no issue, I'll edit the question

If still not working, then create a simple compilable and runnable program that demonstrates your problem and that uses online images available to all, an sscce.

To clarify, at the bottom of the screen I want a JLabel at the far right corner, then in the swing timer, the JLabel will gradually move to the left until it leaves the screen. If I could get setLocation to work, the basic premise would be to have a variable x set to 600, and then every second decrement x by say 50 and then redraw the JLabel at the new location on the screen. Basic animation.

@awestover89: please see edit 3 and edit 4 for an example of what I'm talking about, both sscce-size and animation-wise.

swing - Java Animate JLabel - Stack Overflow

java swing animation timer awt