使用JTextArea和Scanner JAVA打字机效果

时间:2018-04-29 13:00:53

标签: java timer jtextarea

我和我的队友一起为学校项目做比赛 我创建了一个JTextArea,其中将打印文本文件的行 我想添加typeWriter效果,因此我在这个网站上搜索了答案 我在这里找到了一些很好的信息:
java-add-typewriter-effect-to-jtextarea using-timer-to-achieve-typewriter-effect-in-jtextarea 我尝试了上面的解决方案,没有成功。

我会把我的代码:

    public static void slowDisplay(String line, JTextArea textArea){
    Timer timer = new Timer(500, null);
    timer.addActionListener(new ActionListener(){
        int index=0;

        @Override
        public void actionPerformed(ActionEvent e) {
          if(index<line.length()){
              textArea.append(String.valueOf(line.charAt(index++)));
          }
          else if(index==line.length()){
              textArea.append("\n");
          }
          else{
              timer.stop();
          }
        }

    });
    timer.start();

}

这是slowDisplay方法的内容:

        var request = new CreateTableRequest
        {
            TableName = TABLE_CREATE_ACCOUNT,
            AttributeDefinitions = new List<AttributeDefinition>()
            {
                new AttributeDefinition
                {
                    AttributeName = "CommandId",
                    AttributeType = ScalarAttributeType.S
                }
            },
            KeySchema = new List<KeySchemaElement>()
            {
                new KeySchemaElement
                {
                    AttributeName = "CommandId",
                    KeyType = KeyType.HASH
                }
            },
            ProvisionedThroughput = new ProvisionedThroughput
            {
                ReadCapacityUnits = 1,
                WriteCapacityUnits = 1
            },
            StreamSpecification = new StreamSpecification
            {
                StreamEnabled = true,
                StreamViewType = StreamViewType.NEW_IMAGE
            }
        };

        try
        {
            var response = _db.CreateTableAsync(request);
            var tableDescription = response.Result.TableDescription;
            Console.WriteLine("{1}: {0} ReadCapacityUnits: {2} WriteCapacityUnits: {3}",
                tableDescription.TableStatus,
                tableDescription.TableName,
                tableDescription.ProvisionedThroughput.ReadCapacityUnits,
                tableDescription.ProvisionedThroughput.WriteCapacityUnits);
            string status = tableDescription.TableStatus;
            Console.WriteLine(TABLE_CREATE_ACCOUNT + " - " + status);
            WaitUntilTableReady(TABLE_CREATE_ACCOUNT);

            // This connects the DynamoDB stream to a lambda function
            Console.WriteLine("Creating event source mapping between table stream '"+ TABLE_CREATE_ACCOUNT + "' and lambda 'ProcessCreateAccount'");
            var req = new CreateEventSourceMappingRequest
            {
                BatchSize = 100,
                Enabled = true,
                EventSourceArn = tableDescription.LatestStreamArn,
                FunctionName = "ProcessCreateAccount",
                StartingPosition = EventSourcePosition.LATEST
            };
            var reqResponse =_lambda.CreateEventSourceMappingAsync(req);
            Console.WriteLine("Event source mapping state: " + reqResponse.Result.State);
        }
        catch (AmazonDynamoDBException e)
        {
            Console.WriteLine("Error creating table '" + TABLE_CREATE_ACCOUNT + "'");
            Console.WriteLine("Amazon error code: {0}", string.IsNullOrEmpty(e.ErrorCode) ? "None" : e.ErrorCode);
            Console.WriteLine("Exception message: {0}", e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error creating table '" + TABLE_CREATE_ACCOUNT + "'");
            Console.WriteLine("Exception message: {0}", e.Message);
        }

它的作用是浏览文本文件的列并写下字符,它创建了一些可怕的,不可读的东西,我不知道为什么: The thing

我会把我的文字内容写成:

  • -Mmmh ...
  • - 我感到很冷。我在哪里?
  • -Huh?我说谎的东西是人体大小的植物吗?!
  • 我环顾四周,除了树木,灌木丛和植物外什么都没看见。
  • - 什么......

如果有人可以指导我,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

很久以前我也尝试过打字机效果方式。 相反,我使用Thread.sleep()函数来执行此任务。

所以这是方法。

 void typeEffect(String str,JTextArea textArea)throws Exception{

     //loop through each character and append it to the JTextArea
      for(int i==0;i<str.length();i++){

         textArea.append(str.charAt(i)+"");

          Thread.sleep(20);//stops for 20 milliseconds


       }

}

这看起来很简单。

编辑1: -

我已根据需要使用此代码。

 import javax.swing.*;

    class DelayTest
    {

        public static void main(String args[])throws Exception
        {
            JFrame f=new JFrame("Main Frame"); 
            JTextArea textA=new JTextArea();

             f.setSize(720,600);
             f.add(textA);
             f.setVisible(true);
             typeEffect("Hello This is a sample String",textA);
        }

         static void typeEffect(String str,JTextArea textArea)throws Exception{

         //loop through each character and append it to the JTextArea
          for(int i=0;i<str.length();i++){

             textArea.append(str.charAt(i)+"");

              Thread.sleep(100);//stops for 100 milliseconds
             }//closing of loop
         }//closing of method
  }//closing of class

我已执行此代码并发现它正常工作。