缓慢地将文字从字符串打印到JLabel?

时间:2019-02-11 00:26:42

标签: java swing jlabel

我正在尝试在JLabel中进行Pokemon样式的打印,但是由于其限制,我无法成功完成此操作。我能够使用以下代码简单地打印到控制台,从而完成了此任务:

for(int i = 0; i < test.length(); i++) {
        System.out.print(test.charAt(i));
        Thread.sleep(35);
    }

但是,由于JLabel无法接受Char数据类型,因此该方法不起作用。因此,我尝试使用以下方法为该char设置字符串:

while (pos < text.length() - 1) {
            char test = text.charAt(pos);
            String print = String.valueOf(test);
            label.setText(print);
            try {
                Thread.sleep(35);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            pos++;
        }

但是,然后我遇到了文本问题,即在循环中上一次没有添加到文本中。

还有另一种方法可以完成缓慢打印文本的任务吗?

3 个答案:

答案 0 :(得分:2)

Swing不是线程安全的,并且是单线程的。

您不能阻止“事件调度线程”,否则,不会涂上任何东西,并且您不应该从EDT上下文之外更新UI或UI依赖的任何内容

可运行的示例

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private String text = "All your base belong to us";
        private int index;

        private JLabel label = new JLabel("");

        public TestPane() {
            setLayout(new GridBagLayout());
            add(label);

            Timer timer = new Timer(35, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    label.setText(text.substring(0, index));
                    index++;
                    if (index > text.length()) {
                        ((Timer) evt.getSource()).stop();
                    }
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 200);
        }

    }

}

答案 1 :(得分:0)

我很快就一起点击了一些类似于您所需的内容:

/**
 *
 * @author Kai
 */
public class Pokemon extends javax.swing.JFrame {

    String text = "someTesttext";
    StringBuffer current = new StringBuffer();

    /**
     * Creates new form Pokemon
     */
    public Pokemon() {
        initComponents();
        new javax.swing.Timer(150, event -> {
            if (current.length() == text.length()) {
                current.setLength(0);
            } else {
                current.append(text.charAt(current.length()));
            }
            this.jLabel1.setText(current.toString());

        }).start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(400, 400));
        getContentPane().setLayout(null);
        getContentPane().add(jLabel1);
        jLabel1.setBounds(41, 23, 240, 30);

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Pokemon().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

答案 2 :(得分:-2)

您不能只是将字符串放在while循环之外然后添加到其中。 像这样:

String print = ""; // add this line
while (pos < text.length() - 1) {
            char test = text.charAt(pos);
            print = print + String.valueOf(test); // add to the print
            label.setText(print);
            try {
                Thread.sleep(35);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            pos++;
        }