下面的程序基本上调用 JFrame 的frame.repaint()来动态填充框架。 同样,我希望框架有 2 个标签(西和东),并使标签动态变化。 我尝试过很多东西,例如 Jlabel label.repaint()、label.removeAll() 等,但它不起作用。我已经留下了干净的代码,以便您可以填写...
JFrame frame=new JFrame();
frame.setSize(512, 512);
frame.add(image1);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
start_sum=0;
while(true)
{
frame.repaint();
try {
Thread.sleep(sleep_for_each_rotation);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
start_sum+=radian/divide_size; //Some calculation stuff
if(start_sum>=360)
start_sum=0;
}
最佳答案
从代码的外观来看,您正在阻塞事件调度线程 (EDT)。
EDT 负责(除其他事项外)处理重绘事件。这意味着如果您阻止 EDT,则无法重新绘制任何内容。
您遇到的另一个问题是,您永远不应该从 EDT 之外的任何线程创建或修改任何 UI 组件。
看看Concurrency in Swing了解更多详情。
以下示例仅使用 javax.swing.Timer
,但从声音来看,您可能会发现 Swing Worker更有用
public class TestLabelAnimation {
public static void main(String[] args) {
new TestLabelAnimation();
}
public TestLabelAnimation() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JLabel left;
private JLabel right;
public TestPane() {
setLayout(new BorderLayout());
left = new JLabel("0");
right = new JLabel("0");
add(left, BorderLayout.WEST);
add(right, BorderLayout.EAST);
Timer timer = new Timer(250, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
left.setText(Integer.toString((int)Math.round(Math.random() * 100)));
right.setText(Integer.toString((int)Math.round(Math.random() * 100)));
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
}
}
关于java - 如何动态改变JLabel的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14851157/