【发布时间】:2013-12-19 23:32:31
【问题描述】:
我打算为此在我的 JPanel 上绘制一个正方形,但是它没有显示出来。 我做错了什么?
class GUI extends JPanel {
private static Game game = new Game();
...
public GUI () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setAttributes();
makeMenu();
}
});
}
...
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.drawRect(20, 20, 100, 100);
}
}
编辑:代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GUI extends JPanel {
private static Game game = new Game();
private static JPanel panel = new JPanel();
private static JFrame frame = new JFrame();
final private static int FRAME_HEIGHT = 500;
final private static int FRAME_WIDTH = 500;
//Board size 25x25px
final private static int PIXEL_SIZE = 20;
public GUI () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setAttributes();
makeMenu();
}
});
}
public static void setAttributes() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("");
frame.setBackground(Color.black);
frame.setVisible(true);
}
private static void makeMenu() {
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.startGame();
}
});
panel.add(start);
frame.add(panel);
frame.pack();
}
public void setGameFrame() {
panel.removeAll();
frame.setTitle("Snake v0.1");
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.drawRect(20, 20, 100, 100);
}
public void paintGraphics() {
int[][] pixels = Game.getGraphics();
}
}
【问题讨论】:
-
您的代码本身没有显示任何错误,但也没有显示太多。因此,您的错误可能位于未显示的代码中的其他地方。是时候做一些调试了。我确实想知道您的静态游戏变量游戏(静态??),以及您从 JPanel 的构造函数中调用的 invokeLater,这很奇怪,因为该构造函数只能在 EDT 上调用,那么为什么在东部时间在吗?建议:创建并发布sscce。让我们真正看看你做错了什么。
-
这是完整的 GUI 类:pastebin.com/5tDRvwL6 - 我是 Java 新手,所以我可能做错了很多事情。
-
不,请不要这样做,不要在链接中发布代码。您应该调试,您应该努力创建和发布sscce,并且您应该在此处发布您的代码以及您的问题,而不是在链接中。拜托,我们是志愿者,所以努力应该是你的,而不是我们的。
-
我发布它是因为我知道这是一个明显的错误,不需要调试。
-
"I posted it because I know it's an obvious error, that does not need debugging."-- 不...如果很明显,您会发布显示错误的代码,对吗?你没有,所以它显然不是那么明显。通过调试,我的意思是做一些工作来隔离错误。这可以通过 println 语句来完成。例如,如果这是我的错误,而我不知道是什么原因造成的,我会将 println 放在任何地方,我很快就会发现 paintComponent 方法甚至没有被调用。