gpt4 book ai didi

java - 抛硬币程序

转载 作者:搜寻专家 更新时间:2023-11-01 03:26:40 25 4
gpt4 key购买 nike

我尝试编写一个抛硬币的程序(先显示正面图像,然后显示反面图像),但在运行该问题时试图查看硬币图像时遇到了问题;只会显示一个空白屏幕。不知道是jpg图片保存方式不当,还是代码出错。在再次编写显示头部图像和不显示尾部图像的程序之前,我还遇到了一个错误。

CoinTest.java 运行投币器,Coin.java 是该程序的类。

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

public class CoinTest extends JPanel
implements ActionListener
{
private Coin coin;

public CoinTest ()
{
Image heads = (new ImageIcon("quarter-coin-head.jpg")).getImage();
Image tails = (new ImageIcon("Indiana-quarter.jpg")).getImage();
coin = new Coin(heads, tails);

Timer clock = new Timer(2000, this);
clock.start();
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);

int x = getWidth() / 2;
int y = getHeight() / 2;
coin.draw(g, x, y);
}

public void actionPerformed(ActionEvent e)
{
coin.flip();
repaint();
}

public static void main(String[] args)
{
JFrame w = new JFrame("Flipping coin");
w.setSize(300, 300);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

CoinTest panel = new CoinTest();
panel.setBackground(Color.WHITE);
Container c = w.getContentPane();
c.add(panel);

w.setVisible(true);
}
}

现在是实际的 Coin 类。

import java.awt.Image;
import java.awt.Graphics;

public class Coin
{
private Image heads;
private Image tails;
private int side = 1;

public Coin(Image h, Image t)
{
heads = h;
tails = t;
}

//flips the coin
public void flip()
{
if (side == 1)
side = 0;
else
side = 1;
}

//draws the appropriate side of the coin - centered in the JFrame
public void draw(Graphics g, int x, int y)
{
if (side == 1)
g.drawImage(heads, heads.getWidth(null)/3, heads.getHeight(null)/3, null);
else
g.drawImage(heads, tails.getWidth(null)/3, tails.getHeight(null)/3, null);
}
}

最佳答案

首先,确保两张图片都位于正确的加载位置。

其次,你这里有一个错字:

if (side == 1)
g.drawImage(heads, heads.getWidth(null)/3, heads.getHeight(null)/3, null);
else
g.drawImage(heads, tails.getWidth(null)/3, tails.getHeight(null)/3, null);
^^^^

应该是尾部...

关于java - 抛硬币程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327467/

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