1

我需要帮助,因为我正在尝试用 Java 编写游戏。当我发现它不会向 JFrame 绘制字符串时,我停下了脚步。我已经尝试了几种方法来解决这个问题并进行了大量研究,但一无所获。这是代码:- 俄勒冈州(主类):

package com.lojana.oregon.client;

import java.awt.*;

import javax.swing.*;

import com.lojana.oregon.src.Desktop;
import com.lojana.oregon.src.Keyboard;
import com.lojana.oregon.src.Mouse;
import com.lojana.oregon.src.Paint;

public class Oregon extends JFrame {
    private static final long serialVersionUID = 1L;

    // Currently unused but there will be a use for it in the future
    public Desktop desktop;

    public String TITLE = "Oregon";

    public Oregon() {
        /* Window code */
        setTitle(TITLE);
        setSize(640, 640);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        /* Extra code for Window */
        addKeyListener(new Keyboard());
        addMouseListener(new Mouse());
    }

    public void paint(Graphics g) {
        Paint.paint(g);
    }
}

GuiButton(绘画课):

package com.lojana.oregon.src;

import java.awt.*;

public class GuiButton {
    public GuiButton(Graphics g, String text, Font font, int coordX, int coordY,
            int textX, int textY, int width, int height) {
        Color border = Color.gray;
        Color fill = Color.white;
        Color textColor = Color.black;

        Stroke borderSize = new BasicStroke(8);

        g.setColor(border);
        ((Graphics2D) g).setStroke(borderSize);
        g.drawRect(coordX, coordY, width, height);
        g.setColor(fill);
        g.fillRect(coordX, coordY, width, height);
        g.setColor(textColor);
        g.setFont(font);
        g.drawString(text, textX, textY);
    }
}

GuiMainMenu(使用 GuiButton 文件的文件):

package com.lojana.oregon.src;

import java.awt.*;

public class GuiMainMenu {
    public static void paint(Graphics g) {
        new GuiButton(g, "Start Game", new Font("Arial", Font.BOLD, 20), 60, 80, 20, 20, 240, 40);
    }
}

如果您知道如何解决它,请发表评论。非常感谢 :)

4

1 回答 1

5

Swing 程序应该覆盖paintComponent(Graphics g)而不是paint(Graphics g)直接覆盖JFrame. 详情见这篇文章:http: //java.sun.com/products/jfc/tsc/articles/painting/

In addition it would be better to override the paintComponent of a JPanel that is added to the (content pane of) JFrame instead of the JFrame itself, because you want to draw into this content pane. See this tutorial for details: http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html

于 2012-06-10T19:53:51.380 回答