我需要帮助,因为我正在尝试用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);
}
}
吉巴顿(绘画班):
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);
}
}
如果您知道如何修复它,请发表评论。非常感谢:)
Swing 程序应该覆盖paintComponent(Graphics g)
而不是paint(Graphics g)
并直接覆盖JFrame
。有关详细信息,请参阅此文章:http://java.sun.com/products/jfc/tsc/articles/painting/
此外,最好覆盖添加到(内容窗格)JFrame
的JPanel
的paintComponent
,而不是JFrame
本身,因为您要绘制到此内容窗格中。有关详细信息,请参阅本教程:http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html