import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
public class AnimationDemo extends JFrame{
public AnimationDemo(){
add(new MovingMessagePanel("message moving"));
} public static void main(String[] args) {
// TODO Auto-generated method stub
AnimationDemo frame=new AnimationDemo();
frame.setTitle("Animation");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 100);
frame.setVisible(true);
}
static class MovingMessagePanel extends JPanel{
private String message="Welcome to java";
private int xCoordinate=0;
private int yCoordinate=20;
public MovingMessagePanel(String message){
this.message=message;
Timer timer=new Timer(1000,new TimerListener());
timer.start();
}
}
public void paintComponent(Graphics g){
super.paintComponents(g);
if(xCoordinate>getWidth()){
xCoordinate=-20;
}
xCoordinate+=5;
g.drawString(message, xCoordinate, yCoordinate);
}
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
}
}
实在不知道错误在哪,哪位高手帮忙看看
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
public class AnimationDemo extends JFrame{
public AnimationDemo(){
add(new MovingMessagePanel("message moving"));
} public static void main(String[] args) {
// TODO Auto-generated method stub
AnimationDemo frame=new AnimationDemo();
frame.setTitle("Animation");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(280, 100);
frame.setVisible(true);
}
static class MovingMessagePanel extends JPanel{
private String message="Welcome to java";
private int xCoordinate=0;
private int yCoordinate=20;
public MovingMessagePanel(String message){
this.message=message;
Timer timer=new Timer(1000,new TimerListener());
timer.start();
}
}
public void paintComponent(Graphics g){
super.paintComponents(g);
if(xCoordinate>getWidth()){
xCoordinate=-20;
}
xCoordinate+=5;
g.drawString(message, xCoordinate, yCoordinate);
}
class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
repaint();
}
}
}
实在不知道错误在哪,哪位高手帮忙看看
1. 编译不过
把下面paintComponent和TimerListener放到MovingMessagePanel 里面去2.旧的message没有擦掉
public void paintComponent(Graphics g) {
super.paintComponents(g);
Color foreColor = g.getColor();
Color backColor = this.getBackground();
g.setColor(backColor);
g.drawString(message, xCoordinate, yCoordinate);
if (xCoordinate > getWidth()) {
xCoordinate = -20;
}
xCoordinate += 5;
g.setColor(foreColor);
g.drawString(message, xCoordinate, yCoordinate);
}