简体   繁体   English

java paintComponent(graphics g)无法正常工作

[英]java paintComponent(graphics g) won't work

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. 我在paintComponent中的输出告诉我它进入paintComponent内部。 I've googled it for some hours now but I can't find what I'm doing wrong. 我已经用Google搜索了几个小时,但找不到我做错的事情。 The paintComponent is in a class that extends JComponent, as it should. paintComponent位于应扩展JComponent的类中。 I call super.paintComponent(g), not super.paintComponent s (g) and soo on. 我叫super.paintComponent方法(G),不super.paintComponent方法S(G)和洙。 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. 使用setPrefferedSize进行设置。 Also you have to call g.setColor before fillRect. 另外,您必须在fillRect之前调用g.setColor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM