java 跑马灯代码,运行后一动也不动,急死人了,高手快来帮帮忙啊~

2024-11-25 01:29:39
推荐回答(1个)
回答1:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.JWindow;
import javax.swing.Timer;

public class Marquee extends JWindow {
public static String marqueeText;
public static Marquee myMarquee = new Marquee("呜呜~,跑马灯动不了了~ ");
public static JLabel myJLabel = new JLabel(myMarquee.toString());
// 实例化,否则nullpoint
public static Point anchor = new Point();

public Marquee(String marquee) {
marqueeText = marquee;
}

public static void main(String[] args) {
Timer marquee = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {

Point extSize = myMarquee.getLocation();
Dimension viewSize = myJLabel.getPreferredSize();
anchor.x += 5;// 设置移动的速度
myMarquee.setLocation(anchor);
if (anchor.x > viewSize.width) {
anchor.x = -extSize.x;
}

}
});

myJLabel.setForeground(Color.RED);
myJLabel.setOpaque(true);
myJLabel.setPreferredSize(new Dimension(1024, 30));
myMarquee.setVisible(true);
myMarquee.setLocation(0, 0);
myMarquee.setAlwaysOnTop(true);
myMarquee.add(myJLabel);
myMarquee.pack();
// 关键一句,你设置了定时器,但没有让它运行起来,start即可
marquee.start();
}

public String toString() {
return marqueeText;
}

}