1

看了一圈,终于知道怎么调用这个paintComponent()方法了。我现在遇到的问题是这条线g.drawRect(100, 100, 100, 6);实际上并没有绘制矩形。我System.out.println在这行代码的上面和下面放了两个,看看是否真的到达了那一行,它确实到达了。

这是该类的构造函数。最后调用paintComponent() 方法

View(Model m)
{
    this.m = m;

    setTitle("Word Guesssing");
    super.setSize( new Dimension (475, 500) );


    drawPanel  = new JPanel ( new MigLayout() );
    guessPanel = new JPanel ( new MigLayout() );
    wordPanel  = new JPanel ( new MigLayout() );
    guessedLettersPanel = new JPanel ( new MigLayout() );



    setLetterTextFields(); //Adds the letter JTextFields to an ArrayList in the Model class.
    addToGuessPanel(); //Method where components are added to the guessPanel.
    addToWordPanel(); //Method where components are added to the wordPanel. 
    addToGuessedLettersPanel(); //Method where components are added to the guessedLettersPanel.


    //Sets a boarder for each panel.
    wordPanel.setBorder  (new LineBorder(new Color(0, 0, 0)));
    drawPanel.setBorder  (new LineBorder(new Color(0, 0, 0)));
    guessPanel.setBorder (new LineBorder(new Color(0, 0, 0)));
    guessedLettersPanel.setBorder(new LineBorder(new Color(0, 0, 0)));

    //Sets the sizes for each panel
    drawPanel.setPreferredSize(new Dimension (475, 500));
    wordPanel.setPreferredSize ( new Dimension(450, 50) );
    guessPanel.setPreferredSize( new Dimension(350, 100) );
    guessedLettersPanel.setPreferredSize( new Dimension(125, 600) );


    setRadioButtonGroup();

    addToPane();

    setVisible(true);
    setResizable(false);

    paintComponent(drawPanel.getGraphics());
}

这是paintComponent()方法

public void paintComponent( Graphics g )
{
    System.out.println("here 1");
    g.drawRect(100, 100, 100, 6);
    System.out.println("here 2");
}
4

1 回答 1

3

确保repaint()按照 Kayaman 的建议进行操作,但可能更大的问题是在paintComponent 中您不调用超类的paintComponent。尝试添加super.paintComponent(g)到该函数的顶部。

编辑:你应该让它扩展一个 JPanel,然后如果你希望它出现,则将它添加到 JFrame。考虑这个问题的一个好方法是 JFRame 是窗口,但是 JComponents(一个 JPanel 是一个 JComponent)告诉窗口要绘制什么

于 2013-11-09T15:31:00.090 回答