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();
}
}
当这个程序执行时,我看到了这样的效果。是否有可能消除它(零必须改为点)?
答案 0 :(得分:4)
而不是setSize()
使用pack()
来利用组件精心计算的首选大小。您还需要初始化标签:
labels[i] = new JLabel("10000000000000000000000000000000000000");
还要考虑javax.swing.Timer
而不是单独的线程。
附录:方便地,每个Swing Timer
共享一个共同的后台线程,并在事件派发线程上调用actionPerformed()
。另一种方法是SwingWorker
,图示为here。
答案 1 :(得分:3)
我的答案代码只是示例,
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.*;
public class Demo {
private JFrame jf;
private JLabel[] labels;
private JPanel panel;
public Demo() {
labels = new JLabel[10];
Box vbox = Box.createVerticalBox();
for (int i = 0; i < 10; i++) {
labels[i] = new JLabel();
labels[i].setText("10000000000000000000000000000000000000");
vbox.add(labels[i]);
}
panel = new JPanel();
panel.setLayout(new GridLayout());
panel.add(vbox);
jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(panel);
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new DemoRunnable());
}
public void updateState() {
for (final JLabel l : labels) {
if (Math.random() > 0.5) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
l.setText("777777777777777777777777777777777777");
}
});
} else {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
l.setText("10000000000000000000000000000000000000");
}
});
}
}
}
}
class DemoRunnable implements Runnable {
private 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(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
demo.updateState();
}
}
});
t.start();
}
}