4

コインを弾くプログラムを作成しようとしました (最初に表の画像を表示し、後で裏の画像を表示します)。問題を実行したときにコインの画像を表示しようとして問題が発生しました。空白の画面のみが表示されます。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);
}
}
4

2 に答える 2

2

まず、両方の画像がロードする正しい場所にあることを確認してください。

第二に、ここにタイプミスがあります:

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

しっぽのはず…

于 2012-09-08T02:24:14.597 に答える