Reputation: 77
When I run my code it doesn't show up. Basically I have a custom Jcomponent which I add to my JFrame or View and then create a View that makes the frame in my main method. I already added to JFrame here is my code for the JComponent:
public class CardDisplay extends JComponent {
private Card card;
private Image cardImage;
public CardDisplay()
{
cardImage = Toolkit.getDefaultToolkit().createImage(("Phase10//res//Blue2.png"));
}
@Override
public void paint(Graphics g)
{
g.drawImage(cardImage, 125 ,200, this);
}
public class View {
public View(){
}
public void makeFrame()
{
JFrame frame = new JFrame("Phase 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel handPanel = new JPanel();
CardDisplay cd = new CardDisplay();
handPanel.setLayout(new FlowLayout());
frame.add(handPanel, BorderLayout.SOUTH);
handPanel.add(cd);
frame.pack();
frame.setSize(600,500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args){
View view = new View();
Game game = new Game();
view.makeFrame();
//game.run();
}
Upvotes: 2
Views: 1012
Reputation: 5410
Here is the working version. The problem was mainly related to the preferred size of the component. Please note the implementation of method getPreferredSize()
.
If you would like to see what are the component boundaries I'd recommend using MigLayout layout manager in debug mode (the site has all necessary documentation).
public class CardDisplay extends JComponent {
private BufferedImage cardImage;
public CardDisplay() {
try {
cardImage = ImageIO.read(new File("Phase10//res//Blue2.png"));
} catch (final IOException e) {
e.printStackTrace();
}
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.drawImage(cardImage, 0, 0, null);
}
@Override
public Dimension getPreferredSize() {
if (cardImage == null) {
return new Dimension(100, 100);
} else {
return new Dimension(cardImage.getWidth(null), cardImage.getHeight(null));
}
}
public static class View {
public View() {}
public void makeFrame() {
final JFrame frame = new JFrame("Phase 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
final JPanel handPanel = new JPanel();
final CardDisplay cd = new CardDisplay();
handPanel.setLayout(new FlowLayout());
frame.add(handPanel, BorderLayout.SOUTH);
handPanel.add(cd);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
public static void main(final String[] args) {
final View view = new View();
view.makeFrame();
}
}
Upvotes: 3
Reputation: 923
For JComponents, you use paintComponent instead of paint. Paint is actually used to draw components while paintComponent is used to draw images.
Upvotes: 2