我需要一种简单的方法来制作可以在JLabel中使用的方法。我想制作.write(一些文字);每当我调用jLabel.write(一些文本)时的方法;它会逐字写出一些文字。我可以使用控制台轻松完成此操作,但我现在知道如何在JLabel中执行此操作。
示例代码:
public void write(String a) {
char letter;
String word = "";
for(int i = 0; i < a.length(); i++) {
letter = a.charAt(i);
this.setText(word + letter);
word = word + letter;
try {
Thread.sleep(100);
} catch(Exception e) {
}
}
}
...
text.write("Hello");
由于显而易见的原因,这不起作用。但有没有办法实现呢?
答案 0 :(得分:2)
以下是您希望获得的标签的完整示例:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;
public class JPrintLabel extends JLabel {
private Dimension storedSize;
private Timer printTimer;
public void write(final String text) {
// stop old timer if required
if (printTimer != null) {
printTimer.stop();
}
// compute size
if (!isPreferredSizeSet()) {
setText(text);
storedSize = getPreferredSize();
setText("");
}
printTimer = new Timer(200, new ActionListener() {
int counter;
@Override
public void actionPerformed(ActionEvent e) {
if (counter >= text.length()) {
printTimer.stop();
printTimer = null;
} else {
setText(text.substring(0, ++counter));
}
}
});
printTimer.start();
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || storedSize == null) {
return super.getPreferredSize();
} else {
return storedSize;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frm = new JFrame("Test print");
JPrintLabel pl = new JPrintLabel();
frm.add(pl);
pl.write("Here is the text, we want to print!");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
});
}
}
答案 1 :(得分:1)
要做到这一点,我们需要4个步骤:
步骤1和2的新类和方法:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.Timer;
public class MyCustomJLabel extends JLabel{
private String text = "";
public void write(String textToWrite) {
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener(){
int characterCount = 0;
public void actionPerformed(ActionEvent evt){
if (characterCount == textToWrite.length())
{
((Timer)evt.getSource()).stop();
}
getThisLabel().setText(textToWrite.substring(0, characterCount));
characterCount++;
}
};
new Timer(delay, taskPerformer).start();
}
private MyCustomJLabel getThisLabel(){
return this;
}
}
主要方法的新功能执行第3步:
MyCustomJLabel myLabel = new MyCustomJLabel():
myForm.add(myLabel);
第4步,您可以使用myLabel.write
:
myLabel.write("my text to print 1 letter at a time");
感谢Sergiy Medvynskyy的评论,代码已经更正。