gpt4 book ai didi

java - 我的程序一直生成四次?

转载 作者:行者123 更新时间:2023-12-01 11:46:37 25 4
gpt4 key购买 nike

由于某种原因,当我运行这个程序而不是输出一张卡选择时,我得到 3 个,有时是 4 个。

我试图从数组列表中选择一个名称并将其包含在路径中,然后输出图像,您可以在系统输出中看到结果。

代码如下:

public class Main {

public static void main (String[] args) {

Main.createScreen();

}

public static void createScreen() {

JFrame p = new JFrame("Angora Realms");
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GameGUI g = new GameGUI();
p.add(g);
p.setLocationRelativeTo(null);
p.pack();
p.setVisible(true);

}
}

这是我创建 GUI 和绘画的地方:

@SuppressWarnings("serial")
public class GameGUI extends JPanel implements ActionListener {

public Button drawCard = new Button("Draw Card");

public GameGUI() {
drawCard.addActionListener(this);
add(drawCard);
}

@Override
public void actionPerformed(ActionEvent event) {

Object cause = event.getSource();

if (cause == drawCard) {
System.out.println("Ay");
repaint();
}
}


@Override
public void paintComponent(Graphics g) {

super.paintComponent(g);
Cards c = new Cards();
g.drawImage(c.getImage(), 0, 0, 450, 700, this);
}
}

这里是我选择加载什么卡的地方:

public class Cards {

static Random random = new Random();

public static String getCard() {

String card = null;
String[] possibleCards = new String[] {"Cheetah", "Lion"};

card = possibleCards[random.nextInt(2)];
System.out.println(card);

return card;

}

public Image getImage() {

Image img = null;

try {
img = ImageIO.read(getClass().getResource("/dev/angora/images/plains/" + Cards.getCard() + ".png"));
}
catch (IOException e) {
e.printStackTrace();
}

return img;
}

}

当我运行代码时,我得到 4 个猎豹和狮子随机变体的系统打印输出。之前有人告诉我,我实际上在某处创建了我的代码的 3 个实例,但我不知道在哪里......

最佳答案

您并不完全决定如何以及何时执行paintComponent(),这通常并不重要,因为该方法应该做的就是绘制组件。。当您执行 repaint() 时,它会被调用,但当 Swing 认为 UI 需要更新时(可能是窗口更改焦点时,它也会被调用),它也会被调用。调整大小或一堆其他原因)。

但是,您赋予了它一些不应该承担的责任 - 实例化 Cards

Cards c = new Cards();paintComponent() 移动到 actionPerformed(ActionEvent event) 它所属的位置,您应该很好。

关于java - 我的程序一直生成四次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29091237/

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