字符渲染在一段时间后停止工作

huangapple go评论77阅读模式
英文:

<Swing> Character rendering stops working after a while

问题

我正在制作一个小程序矩阵动画和字符渲染在一段时间后停止工作我认为随机操作太慢了因为如果你做同样的事情但不使用随机并在for循环中获取字符则一切正常运行

这是我的代码

import javax.swing.*;
import java.awt.*;
import java.util.SplittableRandom;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestClass {

    // ...(代码的其余部分)

    private static void initAlphabet() {
        alphabet = new char[96];
        int n = 0;
        for (char c = '\u30A0'; c <= '\u30FF'; c++) {
            alphabet[n] = c;
            n++;
        }
    }

    private static void setFrame() {
        frame = new JFrame("Matrix Animation");
        frame.setSize(900, 900);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setVisible(true);

        frame.add(panel);
    }

    private static void setPanel() {
        panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);

                g.setColor(Color.GREEN);

                for (Columns column : Columns.values()) {
                    g.setFont(column.font);
                    g.drawString(String.valueOf(charToDraw), column.xCoords, 22);
                }
            }
        };
        panel.setBackground(Color.BLACK);
    }

    private static void paintChar() {
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(() -> {

            charToDraw = alphabet[random.nextInt(97)];

            panel.repaint();

        }, 0, 200, TimeUnit.MILLISECONDS);
    }

    private static void setCoordColumn() {
        int n = 0;
        for (Columns column : Columns.values()) {
            column.xCoords = n;
            column.font = new Font("ms mincho", Font.ROMAN_BASELINE, random.nextInt(10) + 12);
            n += 30;
        }
    }
}

import java.awt.*;

public enum Columns {
    Column1,
    Column2,
    Column3,
    // ...(省略了其余的列)

    public int xCoords;
    public Font font;
}

我不知道如何进行优化。此外,在绘制符号时使用循环可能不是最优解决方案。但目前来看,Graphics g 是能够处理的。

谢谢)


<details>
<summary>英文:</summary>
I&#39;m making a small program Matrix Animation and - Character rendering stops working after a while. I think that Random is too slow, because if you do the same thing, but not with Random and take characters in the &quot;for&quot; loop, everything works fine.
It&#39;s my code.

import javax.swing.;
import java.awt.
;
import java.util.SplittableRandom;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestClass {

private static JFrame frame;
private static JPanel panel;
private static volatile char charToDraw = &#39;\u30A0&#39;;
private static  char[] alphabet;
private static SplittableRandom random = new SplittableRandom();
public static void main(String[] args) {
initAlphabet();
setCoordColumn();
setPanel();
setFrame();
paintChar();
}
private static void initAlphabet() {
alphabet = new char[96];
int n = 0;
for (char c = &#39;\u30A0&#39;; c &lt;= &#39;\u30FF&#39;; c++) {
alphabet[n] = c;
n++;
}
}
private static void setFrame() {
frame = new JFrame(&quot;Matrix Animation&quot;);
frame.setSize(900, 900);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.add(panel);
}
private static void setPanel() {
panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
for (Columns column : Columns.values()) {
g.setFont(column.font);
g.drawString(String.valueOf(charToDraw), column.xCoords, 22);
}
}
};
panel.setBackground(Color.BLACK);
}
private static void paintChar() {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(() -&gt; {
charToDraw = alphabet[random.nextInt(97)];
panel.repaint();
}, 0, 200, TimeUnit.MILLISECONDS);
}
private static void setCoordColumn() {
int n = 0;
for (Columns column : Columns.values()) {
column.xCoords = n;
column.font = new Font(&quot;ms mincho&quot;, Font.ROMAN_BASELINE, random.nextInt(10) + 12);
n += 30;
}
}

}

import java.awt.*;

public enum Columns {
Column1,
Column2,
Column3,
Column4,
Column5,
Column6,
Column7,
Column8,
Column9,
Column10,
Column11,
Column12,
Column13,
Column14,
Column15,
Column16,
Column17,
Column18,
Column19,
Column20,
Column21,
Column22,
Column23,
Column24,
Column25,
Column26,
Column27,
Column28,
Column29,
Column30;

public int xCoords;
public Font font;

}

I don&#39;t know how to optimize it.
Also, a loop in drawing a symbol is probably not the optimal solution. But so far, Graphics g is coping.
Thanks)
</details>
# 答案1
**得分**: 1
问题在于您的字母数组只有长度为96(这意味着有效索引从0到95,包括0和95):
```java
alphabet = new char[96];

但是在您的 paintChar() 方法中,您将其视为包含97个元素:

charToDraw = alphabet[random.nextInt(97)];

一旦随机生成器返回96,这段代码将抛出 ArrayIndexOutOfBoundsException 异常。

当异常发生时,计划的线程会自动终止。

要解决这个问题,请用以下代码替换上述行:

charToDraw = alphabet[random.nextInt(alphabet.length)];
英文:

The problem is that your alphabet array only has a length of 96 (which means that valid indizes are from 0 to 95 inclusive):

alphabet = new char[96];

but in your paintChar() method you treat is as containing 97 elements:

charToDraw = alphabet[random.nextInt(97)];

This code will throw an ArrayIndexOutOfBoundsException as soon as the random generator returns 96.

The scheduled thread is automatically terminated when an exception occurs.

To fix this replace the line above with

charToDraw = alphabet[random.nextInt(alphabet.length)];

huangapple
  • 本文由 发表于 2020年9月19日 13:41:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63965622.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定