I have two classes in my project, Client and Card. When I try to import an image into the Card class, the paintComponent method in the client does not start. The timer still fires, and and outputs after repaint in the timer listener still print. The cause of this problem appears to be the try catch in the constructor of the card.
package card;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Card {
BufferedImage cardImage;
Point loc = new Point(50, 50);
int scale = 1;
public Card(){
try {
cardImage = ImageIO.read(new File("Penguins.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g2){
g2.setColor(Color.GRAY);
if(cardImage == null)
g2.fillRect(loc.x, loc.y, 150, 225);
else
g2.drawImage(cardImage, loc.x, loc.y, 50, 150, null);
}
}
New class
package core;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import card.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Client extends JPanel {
ArrayList<Card>[] board;
Card card;
Timer timer;
static Client player;
public static void main(String[] args) {
JFrame window = new JFrame("Game");
window.setSize(1080, 720);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
window.setLocation(50, 50);
window.setBackground(Color.GREEN);
player = new Client();
window.setContentPane(player);
}
public Client() {
//board = new ArrayList<Card>[4];
card = new Card();
ActionListener game = new TimerListener();
timer = new Timer(100, game);
timer.start();
}
public class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.BLACK);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(5));
g2.drawOval(15, 75, 200, 200);
g2.drawOval(15, 350, 200, 200);
g2.drawRoundRect(355, -10, 450, 60, 15, 15);
g2.drawRoundRect(230, 75, 700, 90, 20, 20);
g2.drawRoundRect(230, 190, 700, 90, 20, 20);
g2.drawRoundRect(230, 350, 700, 90, 20, 20);
g2.drawRoundRect(230, 475, 700, 90, 20, 20);
g2.drawRoundRect(355, 590, 450, 90, 15, 15);
g2.drawRoundRect(950, 75, 90, 90, 10, 10);
g2.drawRoundRect(950, 190, 90, 90, 10, 10);
g2.drawRoundRect(950, 350, 90, 90, 10, 10);
g2.drawRoundRect(950, 475, 90, 90, 10, 10);
card.draw(g2);
}
}