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.setPaint(getBackground()); g2.fillRect(0, 0, getWidth(), getHeight()); //Draw the circle g2.setPaint(Color.BLUE); g2.fillOval((int)ball.getX(), (int)ball.getY(), ball.getRadius() * 2, ball.getRadius() * 2); } }; displayPanel.setBackground(Color.BLACK); //... "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; panel.add(displayPanel, c);
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!