如何“初始化”我的图形?

时间:2013-09-18 17:12:39

标签: graphics draw shape init

我的朋友让我成为一个简单的JFrame,我本来打算开发它并开发它。我在最初的30分钟内遇到了一个问题:它没有绘制图形!!

以下是绘制图形的代码,以及调出JFrame的类中的代码。

提前致谢。

GameCanvas.java

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package danielballtest;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.util.LinkedList;

/**
*
* @author Kris
*/
public class GameCanvas extends Canvas{
Player p;
LinkedList<Stalker> s = new LinkedList<>();

public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    p.paintItAll(g2d);
    for(int i = 0; i < s.size(); i++) {
        s.get(i).paintItAll(g2d);
    }
}

public GameCanvas() {
    initComponents();
    repaint();
}

public void initComponents() {
    p = new Player(new Point(50,50));
    s.add(new Stalker(new Point(50,100)));
}

public Point getPlayerPos() {
    return p.getPos();
}
}





MainWindow.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package danielballtest;

import java.awt.BorderLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
*
* @author Kris
*/
public class MainWindow extends JFrame{
static Toolkit tk = Toolkit.getDefaultToolkit();
static int xSize = ((int) tk.getScreenSize().getWidth());
static int ySize = ((int) tk.getScreenSize().getHeight());
/**
 * @param args the command line arguments
 */
public MainWindow() {
    super("STALKER!!!!!!!!!!");
    GameCanvas canvas = new GameCanvas();
    add(canvas, BorderLayout.CENTER);
    setSize(xSize, ySize);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);      
    canvas.createBufferStrategy(2);
}
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new MainWindow();
        }
    });
}
}

1 个答案:

答案 0 :(得分:1)

您使用旧的AWT Canvas类作为基本组件。此类遵循AWT绘制机制,其中没有paintComponent方法,您应该覆盖paint来执行自定义图形。

将基类更改为JComponent,您可以使用更新的绘制机制:

...
import javax.swing.JComponent;

public class GameCanvas extends JComponent {

This article比较了绘画在AWT和Swing中的效果,如果你想了解更多关于它们的话。