如何使用 graphics2D 显示 1 到 10 之间的随机数?

How can I show a random number between 1 to 10 with graphics2D?

我正在考虑如何创建它,我可以在一个线程上使用 System.out.println 创建它,它运行良好,但是,我正在询问如何每秒显示随机数据,使用方法Graphics2D,有人可以帮忙吗?

这是我所做的:

String[] numbers= {"1","2", "3", "4", "5", "6", "7", "8", "9", "10"};
int random = (int) (Math.random()*numbers.length);

//here's the part I struggle
public void paint (Graphics g) {
    g2.setColor(Color.black);
    g2.drawString("The number is below", 50, 70);

    //won't run
    g2.draw(numbers, 50, 90);
}

方法draw in Graphics2D takes a Shape not a String. You should be using the drawString方法。

在使用 drawString 方法时,您需要将您的值转换为 String。您可以使用 String.join(", "numbers)。但是,如果您想显示 random 值而不是数字,您可以使用 String.valueOf(random) 来转换它。

对代码的更改将是

g2.drawString(String.join(", ", numbers), 50, 90);

g2.drawString(String.valueOf(random), 50, 90);

您可以创建一个面板,生成从最小值到最大值的随机数。

首先,这是不正确的。您在此之前的通话中正确使用了 drawString

g2.draw(numbers, 50, 90); // draw is not a method of Graphics2D

其次,除非您的数组不是整数,否则您可以按原样显示随机值。

String.format("%d", getRandomInteger()) // Display a random number as a string

最后,在 JComponent(摆动)中,您必须覆盖 paintComponent 而不是 paint。在您的示例中,您可以只使用标准图形 (g.drawString)。

@Override
protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g; // Optional, has more methods

}
import java.awt.*;
import javax.swing.*;

public class RandomNumberPanel extends JPanel {
    private static final long serialVersionUID = -4376447503776020320L;
    private int min;
    private int max;

    public RandomNumberPanel() {
        this(0, 10);
    }

    public RandomNumberPanel(int max) {
        this(0, max);
    }

    public RandomNumberPanel(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public int getRandomInteger() {
        return getRandomInteger(min, max);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.BLACK);
        g2.drawString("The number is below", this.getWidth() / 4, this.getHeight() / 3);
        g2.drawString(String.format("%d", getRandomInteger()), this.getWidth() / 2, this.getHeight() / 2);
    }

    public static final int getRandomInteger(final int max, final int min) {
        return ((int) (Math.random() * (max - min))) + min;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame mainFrame = new JFrame();
                JPanel panel = new RandomNumberPanel(1, 10); // [1, 10]

                panel.setPreferredSize(new Dimension(200, 100));
                mainFrame.setContentPane(panel);
                mainFrame.pack();
                mainFrame.setLocationRelativeTo(null);
                mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                mainFrame.setVisible(true);
            }
        });
    }
}