Donnerstag, 2. Oktober 2008

Java Hearts Remarks1

EE3206/EE5805 Java Porgramming and Applications

How to draw cards on the JPanel?

1. Whenever a component is displayed, the jvm automatically creates a Graphics object for the component on the native platform.

eg Graphics graphics = jpanelcanvas.getGraphics();

2. In order to draw things on a component eg JPanel
consistently, you need to declare a class that
extends a Swing GUI component class an overrides
its paintComponent method to specify what to draw

3. ImageIcon imageicon = new ImageIcon("CardImg/36.png");
Image qimage = imageicon.getImage();
g.drawImage(qimage, 40, 40, 72, 96, this);

////////////////////////////////////////////////////

import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;


public class DrawQueen extends JFrame
{
// paint a quueen card image
//In order to draw things on a component eg JPanel
// consistently, you need to declare a class that
// extends a Swing GUI component class an overrides
//its paintComponent method to specify what to draw


public DrawQueen()
{
add (new DrawPanel() );
}

public static void main (String[] args)
{
DrawQueen frame = new DrawQueen();

frame.setTitle("Draw a Queen on a JPanel component");
frame.setSize(500,400);
frame.setLocationRelativeTo(null); //centre the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

}



class DrawPanel extends JPanel
{

ImageIcon imageicon = new ImageIcon("CardImg/36.png");
ImageIcon imageicon2 = new ImageIcon("CardImg/35.png");
ImageIcon imageicon3 = new ImageIcon("CardImg/12.png");
ImageIcon imageicon4 = new ImageIcon("CardImg/13.png");

Image qimage = imageicon.getImage();
Image rimage = imageicon2.getImage();
Image simage = imageicon3.getImage();
Image timage = imageicon4.getImage();

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(0,0,50,50);
g.drawString("Player 1", 0, 40);

if (qimage != null )
{
g.drawImage(qimage, 40, 40, 72, 96, this);
g.drawImage(rimage, 60, 40, 72, 96, this);
g.drawImage(simage, 80, 40, 72, 96, this);
g.drawImage(timage, 100, 40, 72, 96, this);
}

}
}

Keine Kommentare: