I am new to this community and have a question about Java POO. It's about implementing a timer. The question is: why I cannot get a timer with a period of 1 ms. When I chose a period of e.g. 10 ms, everything works fine, but Java (or the computer?) looks like periods approaching 1 ms are ignored. The program (not really OOP oriented, sorry for that) should display a value every second. OK, I could use a delay of 1000 ms, but it must be also possible my way. I write another (graphics) application where the 1 ms period is important, but I chose this demo program to show to you. I my demo, a display is done only around every 10 seconds, but it should be 1 second.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class NewJFrame extends javax.swing.JFrame {
private int counter = 0;
public NewJFrame() {
initComponents();
timer.start();
}
Timer timer = new Timer(1, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
if (counter%1000==0)
jLabel1.setText("ping");
}
});
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(180, 180, 180)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(139, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(131, 131, 131)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(134, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
new NewJFrame().setVisible(true);
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
I expect the timer to work with a minimal period of 1 ms, as described in the docs.