【发布时间】:2021-09-07 21:17:24
【问题描述】:
谁能给我一些建议,我该怎么做?我在互联网上找到了一些代码,但我不知道如何使用它如何将其添加到我的代码中并使用它,因为该代码会自行创建一个框架。
如何将JLabel 分配给此代码?
这是代码(我想将它用于我创建的框架上的标签):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
public class JScrollingText extends JLabel {
private int speed;
private int period;
private int offset;
private int x;
public JScrollingText(String text) {
this(text, 1);
}
public JScrollingText(String text, int speed) {
this(text, speed, 100);
}
public JScrollingText(String text, int speed, int period) {
this(text, speed, period, 0);
}
public JScrollingText(String text, int speed, int period, int offset) {
super(text);
this.speed = speed;
this.period = period;
this.offset = offset;
}
public void paintComponent(Graphics g) {
if (isOpaque()) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
g.setColor(getForeground());
FontMetrics fm = g.getFontMetrics();
Insets insets = getInsets();
int width = getWidth() - (insets.left + insets.right);
int height = getHeight() - (insets.top + insets.bottom);
int textWidth = fm.stringWidth(getText());
if (width < textWidth) {
width = textWidth + offset;
}
x %= width;
int textX = insets.left + x;
int textY = insets.top + (height - fm.getHeight()) / 2 + fm.getAscent();
g.drawString(getText(), textX, textY);
g.drawString(getText(), textX + (speed > 0 ? -width : width), textY);
}
public void start() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
x += speed;
repaint();
}
};
timer.scheduleAtFixedRate(task, 0, period);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JButton quit = new JButton("Quitter");
quit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(quit);
JScrollingText scrollingText1 = new JScrollingText("Barre des tâches... Pressez le bouton Quitter", -3);
scrollingText1.setBorder(BorderFactory.createEtchedBorder());
scrollingText1.start();
frame.getContentPane().add(scrollingText1, BorderLayout.NORTH);
JScrollingText scrollingText2 = new JScrollingText("Barre des tâches... Pressez le bouton Quitter");
scrollingText2.setBorder(BorderFactory.createEtchedBorder());
scrollingText2.start();
scrollingText2.setBackground(Color.YELLOW);
scrollingText2.setOpaque(true);
frame.getContentPane().add(scrollingText2, BorderLayout.SOUTH);
frame.setVisible(true);
}
}
【问题讨论】:
-
1) 不要扩展 JLabel。 JLabel 已经有自定义绘画代码。扩展 JComponent 或 JPanel 以添加您的自定义绘画代码。 2) 不要将 AWT 定时器用于动画。所有 Swing 组件都应在
Event Dispatch Thread (EDT)上更新。所以你应该使用Swing Timer 来制作动画。 3) 查看Marquee Panel 了解一种方法。
标签: java swing user-interface jlabel