gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:18:57 25 4
gpt4 key购买 nike

我正在考虑如何创建它,我可以在线程上使用 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);
}

最佳答案

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

首先,这是不正确的。您在此之前的调用中正确使用了 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 (swing) 中,您必须重写 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);
}
});
}
}

关于java - 如何使用 Graphics2D 显示 1 到 10 之间的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com