所以我正在创建一个游戏,我需要多种方法来输出文本(到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);
}
}
}
答案 0 :(得分:0)
您需要调用 getGraphics()来从 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);
}
}