日期:2014-05-20  浏览次数:20830 次

大家帮忙看看为什么我的面板不显示内容
学习了Timer类,就按照书上的代码写了个消息在面板上移动的代码,但是现在消息不显示出来?怎么回事嗯?大家帮忙看看~
Java code

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class AnimationDemo extends JFrame {
    public AnimationDemo() {
        add(new MovingMessagePanel("message moving"));
    }
    
    public static void main(String[] args) {
        AnimationDemo frame = new AnimationDemo();
        frame.setTitle("AnimationDemo");
        frame.setSize(280, 100);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    
    static class MovingMessagePanel extends JPanel {
        public MovingMessagePanel(String message) {
            this.message = message;
            
            Timer time = new Timer(1000, new TimerListener());
            time.start();
        }
        
        protected void paintComponet(Graphics g) {
            super.paintComponent(g);
            
            if (x > getWidth()) {
                x = -20;
            }
            x += 5;
            g.drawString(message, x, y);
        }
        
        class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                repaint();
            }
        }
        private int x = 0;
        private int y = 20;
        private String message = "Welcome to Java";
    }
}



------解决方案--------------------
写错函数名了吧?

protected void paintComponet(Graphics g) {

Java code

        @Override
        public void paint(Graphics g) {
            // TODO Auto-generated method stub
            super.paint(g);

            if (x > getWidth()) {
                x = -20;
            }
            x += 5;
            g.drawString(message, x, y);
        }