JFrame不会让我drawString();

时间:2012-06-10 17:54:48

标签: java swing graphics jframe drawstring

我需要帮助,因为我正在尝试用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);
    }
}

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

1 个答案:

答案 0 :(得分:5)

Swing程序应该覆盖paintComponent(Graphics g)而不是paint(Graphics g)并直接覆盖JFrame。有关详细信息,请参阅此文 http://java.sun.com/products/jfc/tsc/articles/painting/

此外,最好覆盖添加到paintComponent的(内容窗格)而不是JPanel本身的JFrame的{​​{1}},因为您想要绘制到此内容窗格中。有关详细信息,请参阅本教 http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html