我试图画一个简单的矩形,但它不会起作用。我在paintComponent中的sout告诉我它在paintComponent中。我已经用谷歌搜索了几个小时,但我无法找到我做错的事情。 paintComponent在一个扩展JComponent的类中,应该如此。我调用super.paintComponent(g),而不是super.paintComponent s (g)和soo。我错过了什么?
import java.awt.*;
import javax.swing.*;
public class Board extends JComponent{
private GameCreator game;
public Board(GameCreator game)
{
this.game = game;
}
@Override
public void paintComponent (Graphics g){
super.paintComponent(g);
g.fillRect(50,50,300,300);
g.setColor(Color.orange);
System.out.println("inside piantComponent");
}
public static void main(String[]args)
{
GameCreator game = new GameCreator(8,10);
game.prepareBoard();
Board board = new Board(game);
new Frame("test", board);
}
}
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame {
Board board;
JPanel gamePanel;
public Frame(String title, Board board) {
super(title);
setLayout(new BorderLayout());
setPreferredSize(new Dimension(800, 800));
pack();
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.board = board;
gamePanel = new JPanel();
gamePanel.add(board);
setContentPane(gamePanel);
}
}
答案 0 :(得分:1)
你的电路板没有尺寸。使用setPrefferedSize设置它。你还必须在fillRect之前调用g.setColor。