JComponent size issue

前端 未结 2 1844
轮回少年
轮回少年 2021-01-22 13:24

I have a JComponent subclass that I am using to draw shapes onto my screen. In the constructor, I am trying to set ballX and ballY to half

相关标签:
2条回答
  • 2021-01-22 13:39

    Override getPreferredSize() in your JComponent to return your preferred size, and start with half the width and height of that Dimension. To the same end, this KineticModel invokes setPreferredSize() in DisplayPanel.

    Addendum: By way of explanation, your current approach fails because the results from getWidth() and getHeight() are invalid until validate() has been called on the enclosing container, typically as the result of pack().

    0 讨论(0)
  • 2021-01-22 13:52

    I agree with trashgod's answer. (+1)

    Move the ballX and ballY in the paintComponent(g) like this

    if (ballX==0 && ballY==0) {
        ballX = getWidth()/2;
        ballY = getHeight()/2;
    }
    
    0 讨论(0)
提交回复
热议问题