0

所以我正在创建一个游戏,我需要多种方法来输出文本(到 JFrame)或显示图像。我创建了一个具有 paintComponent 方法的 GraphicsEngine - 但问题是,这将通过将其添加到 JFrame 而不是通过我的调用来运行,而且我不能调用其他 GraphicsEngine 方法,因为它需要一个 Graphics2D 对象......当我调用方法时我不会有。我将如何制作一堆可以在没有自己的paintComponent 的情况下向JFrame 添加东西的方法?请帮忙。

这是我的 GraphicsEngine,如果有人觉得它是相关的。

import javax.swing.JComponent;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class GraphicsEngine extends JComponent
{
    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        BufferedImage img = null;
        try {
            img = ImageIO.read(new File("Splash.jpg"));
        } catch (IOException e) {
        }
        g2.drawImage(img, 0, 0, null);
    }

    public void textOut (Graphics2D g2, String text){

        for(char c : text.toCharArray()){
            System.out.print(c); //I want to be able to print this to JFrame     through g2's text printing methods.
            delay(30);
        }
    }  
}
4

1 回答 1

0

You need to call getGraphics() to get the graphics from JComponent

public void textOut (String text){

        Graphics2D g2= getGraphics();
        for(char c : text.toCharArray()){
            g2.drawString("StackOverflow",40,20); //add your code with g2 to draw text
            delay(30);
        }
}  
于 2015-03-10T17:22:10.323 回答