问题描述
import javax.swing.*;import java.awt.*;import java.awt.event.*;import java.awt.Graphics;public class MovingCar extends JFrame{public MovingCar(String s){super(s);CarPanel MyCar=new CarPanel();add(MyCar);}public static void main(String [] args){JFrame mine=new MovingCar("my window");mine.setSize(500,300);mine.setLocation(200,200);mine.setVisible(true);}public class CarPanel extends JPanel{public CarPanel(){Timer timer=new Timer(1000,new TimeActionListener());timer.start();}}class TimeActionListener implements ActionListener{public void actionPerformed(ActionEvent g){repaint();}}protected void paintComponent(Graphics g){super.paintComponents(g);int px=0;int py=5;if(px>=getWidth())px=0;px+=5;g.drawString("mmmm",px,py);}} 问题补充:xiexie lchen_yongkai 写道
解决方案
import java.awt.Color;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 MovingCar extends JFrame {public MovingCar(String s) {super(s);CarPanel MyCar = new CarPanel();add(MyCar);}public static void main(String[] args) {JFrame mine = new MovingCar("my window");mine.setSize(500, 300);mine.setLocation(200, 200);mine.setVisible(true);mine.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}public class CarPanel extends JPanel {int px=0;public CarPanel() {Timer timer = new Timer(200, new TimeActionListener());timer.start();}class TimeActionListener implements ActionListener {public void actionPerformed(ActionEvent g) {repaint();}}protected void paintComponent(Graphics g) {super.paintComponents(g);g.clearRect(0, 0, getWidth(), getHeight());int py = 50;if (px >= getWidth())px = 0;px += 5;g.setColor(Color.red);g.drawString("mmmm", px, py);}}}刚才发错了,我改了一下,可以了
解决方案二:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.Graphics; public class MovingCar extends JFrame { public MovingCar(String s) { super(s); CarPanel MyCar=new CarPanel(); add(MyCar); } public static void main(String [] args) { JFrame mine=new MovingCar("my window"); mine.setSize(500,300); mine.setLocation(200,200); mine.setVisible(true); } public class CarPanel extends JPanel { public CarPanel() { Timer timer=new Timer(1000,new TimeActionListener()); timer.start(); } } class TimeActionListener implements ActionListener { public void actionPerformed(ActionEvent g) { repaint(); } } protected void paintComponent(Graphics g) { super.paintComponents(g); int px=0; int py=5; if(px>=getWidth()) px=0; px+=5; g.drawString("mmmm",px,py); } }