zeja
Erfahrenes Mitglied
Hier mal ein kleines vollständiges Beispiel:
Java:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class CardGame extends JPanel {
private final GameCard[][] cards = new GameCard[25][25];
public CardGame() {
init( );
}
private void init() {
cards[0][0] = new Dog( );
cards[0][1] = new Cat( );
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int row = 0; row < cards.length; row++) {
GameCard[] rowCards = cards[row];
int y = row * 25;
for (int col = 0; col < rowCards.length; col++) {
int x = col * 25;
final GameCard card = rowCards[col];
if (card != null) {
card.paint(g, x, y, 25, 25);
}
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("MyGame");
CardGame game = new CardGame( );
frame.add(game, BorderLayout.CENTER);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setSize(100, 100);
frame.setVisible(true);
}
private static final class Cat implements GameCard {
public void paint(Graphics g, int x, int y, int width, int height) {
g.setColor(Color.RED);
g.fillRect(x, y, width, height);
}
}
private static final class Dog implements GameCard {
public void paint(Graphics g, int x, int y, int width, int height) {
g.setColor(Color.BLUE);
g.fillRect(x, y, width, height);
}
}
interface GameCard {
void paint(Graphics g, int x, int y, int width, int height);
}
}