我尝试制作一个翻转硬币的程序(首先显示头像,后面显示尾部图像),我遇到了问题,试图在处理问题时看到硬币图像;只有一个空白屏幕会显示。我不知道这是来自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);
}
}
我猜想,您的影像未正确加载;仔细检查你的路径是否正确。此外,虽然这可能与问题无关,但Coin#draw中有两个int参数永远不会被使用。 – Vulcan
如果我可以提出一个更简单的方法:不是自己做绘图,而是使用['CardLayout'](http://docs.oracle.com)将每个'ImageIcon'添加到'JLabel'并将其添加到'JPanel'。 COM/JavaSE的/教程/ uiswing /布局/ card.html)。然后当你掷硬币时,你只需要做'cardLayout.show(coinContainer,“heads”)'。 –
我应该指定从C:/?开始的路径吗?我有我的源文件内的图像,然后我转移到Coin项目内部,但在源文件之外。我现在指定/Coin/quarter-coin-head.jpg。 – user1629075