java硬币翻转问题_java – 硬币翻转程序

我尝试制作一个翻转硬币的程序(首先显示头部图像,然后显示尾部图像),当我遇到问题时,我遇到了试图查看硬币图像的问题;只显示一个空白屏幕.我不知道这是来自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);

}

}

现在是实际的硬币类.

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);

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值