【问题标题】:How should I consolidate graphics methods in Java?我应该如何在 Java 中整合图形方法?
【发布时间】:2015-03-08 05:30:31
【问题描述】:

所以我正在创建一个需要多种方法来输出文本(到 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);
        }
    }  
}

【问题讨论】:

  • 关于图像加载的建议:不要每次绘制时都加载图像,这将非常昂贵。 (img = ImageIO.read(new File("Splash.jpg"));) 初始化时加载一次,多次绘制。
  • 我不太明白你的另一个问题,而且我认为我并不孤单。你想做什么,它不起作用怎么办?
  • 1) g2.drawImage(img, 0, 0, null); a JComponent ImageObserver 所以应该是g2.drawImage(img, 0, 0, this);。 2)不要忽略异常,它会回来咬你。 3) 如果未加载图像可能是null,最好在绘画前检查if (img==null) {..。 4) 对被覆盖的方法使用@Override 表示法。 5) 始终首先调用super.paintComponent(g); 方法。 6) 鉴于Splash.jpg 显然是一个应用程序资源,它将在Jar 中并且在运行时不能作为File 使用。通过 URL 加载它。
  • 哦,考虑到编写 9 行方法的 7 个非最佳或损坏的方面,很明显你没有经验。我会首先推荐更简单的项目。在制作游戏时,请考虑使用游戏引擎(希望他们能够正确掌握基础知识)。
  • 它实际上只是将图形添加到我制作的现有基于文本的游戏中。是的,我对此不是很有经验

标签: java swing graphics jframe consolidation


【解决方案1】:

您需要调用 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);
        }
}  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2010-10-07
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多