paintComponent()不会绘制

时间:2013-11-09 14:49:11

标签: java swing jframe paintcomponent

在四处寻找之后,我终于找到了如何实际调用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");
}

1 个答案:

答案 0 :(得分:3)

确保repaint()作为Kayaman的建议,但可能更大的问题是在paintComponent中你没有调用超类的paintComponent。尝试将super.paintComponent(g)添加到该功能的顶部。

编辑:您应该扩展JPanel,然后将其添加到JFrame中,如果您希望它显示的话。考虑这个的一个好方法是JFRame是窗口,但JComponents(JPanel是一个JComponent)告诉窗口要绘制什么