Pesky <JPanel>.getWidth() and <JPanel>.getHeight() Methods...
I am using the size of a JPanel to control the bounds of display for a circle drawn in a program I'm writing. In short, the circle cannot move outside the width or height of the JPanel. However, I'm having trouble discerning the JPanel's width and height...
The JPanel is created using this code:
displayPanel = new JPanel()
public void paintComponent(Graphics g)
//Construct the graphics
Graphics2D g2 = (Graphics2D)g;
//Fill the background black
g2.fillRect(0, 0, getWidth(), getHeight());
//Draw the circle
g2.fillOval((int)ball.getX(), (int)ball.getY(), ball.getRadius() * 2, ball.getRadius() * 2);
//... "displayPanel" is added to a JPanel called "panel" by this code ...
panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
c.weightx = 0.5;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
c.gridheight = 2;
c.ipady = 300;
Later, however, when I try to derive the width and height of displayPanel, it does not work:
However, when ball's constructor calls displayPanel.getWidth() and displayPanel.getHeight(), is receives 0 for both.
//Ball is an object that manages the location of the circle
ball = new Ball(7, 30, 45, 20, 20, displayPanel.getWidth(), displayPanel.getHeight());
Can anyone provide me with a solution to this annoyance? Any help would be greatly appreciated! Thanks!
Re: Pesky <JPanel>.getWidth() and <JPanel>.getHeight() Methods...
Ugh, I feel stupid.
As it so surprisingly turns out (sarcasm dripping from my mouth) you have to set the top level container to visible before Components are lined up and given dimensions. Using that knowledge, I fixed my problem.
I no longer require any help on this matter! :P