我的代码如下,执行后就是没效果,不知错在哪里
import java.awt.BorderLayout;
public class DynamicIconDemo extends JFrame {
private JPanel contentPane;
public JLabel label;
private class IconMotion implements Runnable{
@Override
public void run(){
// label.setText("123");
for(int i=0;i<340;i++){
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
label.setBounds(10+i,10,72,72);
}
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DynamicIconDemo frame = new DynamicIconDemo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
DynamicIconDemo di=new DynamicIconDemo();
DynamicIconDemo.IconMotion im=di.new IconMotion();
Thread thread=new Thread(im);
thread.start();
}
/**
* Create the frame.
*/
public DynamicIconDemo() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 358, 237);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel label = new JLabel("1");
label.setIcon(new ImageIcon(DynamicIconDemo.class.getResource("/javax/swing/plaf/metal/icons/Warn.gif")));
label.setBounds(23, 70, 72, 38);
contentPane.add(label);
}
}
------解决方案--------------------
参考下下面的代码
- Java code
import java.awt.EventQueue;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.EmptyBorder;public class DynamicIconDemo extends JFrame { /** * */ private static final long serialVersionUID = 1L; private JPanel contentPane; public JLabel label; private class IconMotion implements Runnable { @Override public void run() { // label.setText("123"); for (int i = 0; i < 340; i++) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } label.setBounds(10 + i, 10, 72, 72); } } } /** * Launch the application. */ public static void main(String[] args) { final DynamicIconDemo di = new DynamicIconDemo(); EventQueue.invokeLater(new Runnable() { public void run() { try { di.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); DynamicIconDemo.IconMotion im = di.new IconMotion(); Thread thread = new Thread(im); thread.start(); } /** * Create the frame. */ public DynamicIconDemo() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 358, 237); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); label = new JLabel("1"); label.setIcon(new ImageIcon(DynamicIconDemo.class .getResource("/javax/swing/plaf/metal/icons/Warn.gif"))); label.setBounds(23, 70, 72, 38); contentPane.add(label); }}