import java.awt.Graphics;
import javax.swing.*;
public class Demo
{
JFrame jf;
JLabel[] labels;
JPanel panel;
public Demo()
{
jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
labels = new JLabel[10];
Box vbox = Box.createVerticalBox();
for (int i = 0; i < 10; i++)
{
labels[i] = new JLabel();
vbox.add(labels[i]);
}
panel = new JPanel();
panel.add(vbox);
jf.add(panel);
jf.setSize(300, 250);
jf.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new DemoRunnable());
}
public void updateState()
{
for (JLabel l : labels)
{
if (Math.random() > 0.5)
l.setText("777777777777777777777777777777777777");
else
l.setText("10000000000000000000000000000000000000");
}
}
}
class DemoRunnable implements Runnable
{
Demo demo;
DemoRunnable()
{
this.demo = new Demo();
}
@Override
public void run()
{
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
try
{
Thread.sleep(0);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
demo.updateState();
}
}
});
t.start();
}
}
I see such effect when this program is perfomed. Is it possible to eliminate it(zeroes must be instead dots)?
A JLabel object can display either text, an image, or both. You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area.
JLabel does not align the text in the center.
To update the text in a label you use label. setText("New text") .
Instead of setSize()
use pack()
to take advantage of the component's carefully calculated preferred size. You'll also need to initialize your label:
labels[i] = new JLabel("10000000000000000000000000000000000000");
Also consider javax.swing.Timer
instead of a separate thread.
Addendum: Conveniently, each Swing Timer
shares a common background thread, and the actionPerformed()
is called on the event dispatch thread. An alternative is SwingWorker
, illustrated here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With