I tried to create a program that flips a coin (first it shows the image of the heads and then shows the image of the tails), and I ran into problems trying to display the image of the coin when the problem started; only a blank screen will be shown. I do not know if this is due to the wrong way to save jpg images or to an error in the code. I also stumbled upon an error before re-encoding a program where I had an image with a head image and an image of tails not shown.
CoinTest.java launches a coin runner, and Coin.java is the class for the program.
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); } }
Now the current Coin class.
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; }
source share