我正在编写应该是一段简单的代码,用于创建JFrame对象,然后将背景绘制为黑色并绘制蓝色方块。但是,repaint()方法不会调用paintComponent()方法。
这是代码:
import java.util.Vector;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Container;
public class Snake extends JPanel{
private Vector xCoords = new Vector();
private Vector yCoords = new Vector();
public Snake(){
xCoords.add(150);
yCoords.add(150);
}
public void startJFrame(){
JFrame window = new JFrame();
window.setSize(300, 300);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = window.getContentPane();
c.setBackground(Color.black);
}
public void paintRequest(){
System.out.println("Request to paint received.");
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println("paintComponent was called");
g.setColor(Color.blue);
int x = (int)xCoords.get(0);
int y = (int)yCoords.get(0);
g.fillRect(x, y, 10, 10);
}
public static void main(String[] args){
Snake mkFrame = new Snake();
mkFrame.startJFrame();
mkFrame.paintRequest();
}
}
我知道paintRequest()被正确调用,因为它打印“Request to paint received”,但是“paintComponent被调用”永远不会打印出来。在gui端,创建了JFrame窗口,它有一个黑色背景,但没有蓝色方块。提前感谢您的帮助。
答案 0 :(得分:2)
框架中没有添加Snake
!
变化:
JFrame window = new JFrame();
要:
JFrame window = new JFrame();
window.add(new Snake());