【问题标题】:Coin flip program硬币翻转程序
【发布时间】:2012-09-08 02:06:23
【问题描述】:

我尝试制作一个抛硬币的程序(先显示正面图像,然后显示反面图像),但在运行问题时尝试查看硬币图像时遇到了问题;只会显示一个空白屏幕。我不知道这是由于 jpg 图像的不正确保存方法还是代码中的错误。在再次编码显示头部图像而未显示尾部图像的程序之前,我也遇到了一个错误。

CoinTest.java 运行 coin runner,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);
}
}

【问题讨论】:

  • 我猜你的图片加载不正确;仔细检查您的路径是否正确。此外,虽然这可能与问题无关,但 Coin#draw 中有两个 int 参数从未被使用过。
  • 如果我可以提出一个更简单的方法:不要自己绘制,而是将每个 ImageIcon 添加到 JLabel 并使用 CardLayout 将每个添加到 JPanel。那么当你flip()硬币时,你只需要cardLayout.show(coinContainer, "heads")
  • 我应该指定从C:/开始的路径吗?我的源文件中有图像,然后我移到 Coin 项目内部但在源文件之外。我现在指定 /Coin/quarter-coin-head.jpg。
  • 修复了问题,将文件路径一直延伸到 C:。我有不同的图像副本,因此路径在某种程度上是相同的(/Coin/quarter-coin-head.jpg)。我假设编译器不知道我指的是哪些图像。这可能是我在运行程序时没有得到图像的原因吗?感谢大家的帮助

标签: java coin-flipping


【解决方案1】:

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

其次,这里有一个错字:

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

应该是尾巴……

【讨论】:

  • 啊,谢谢你,这就是为什么我最初运行程序时只显示头像的原因。但我将程序转移到另一台计算机上,现在显示图像时出现问题。
  • 已修复。上面修复的解释。
【解决方案2】:

小程序的宽度和高度在标记中编码。绘制小程序的代码使用这两种方法在运行时获取这些值。所以现在,不同的标签可以要求同一个小程序绘制不同大小的矩形。源代码不同大小不需要重新编译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多