I'm trying to paint a simple rectangle, but it won't work. My sout in paintComponent tells me that it gets inside of paintComponent. I've googled it for some hours now but I can't find what I'm doing wrong. The paintComponent is in a class that extends JComponent, as it should. I call super.paintComponent(g), not super.paintComponent s (g) and soo on. What am I missing?
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);
}
}
Your board does not have a size. Set it with setPrefferedSize. Also you have to call g.setColor before fillRect.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.