In your application, you encounter an issue where you need to access the width and height of a JPanel from a separate class (Rect). JPanel provides methods to retrieve its dimensions, but they return 0 when called outside the class.
One solution is to pass the JPanel instance as a parameter to the move() method in the Rect class. This provides access to the JPanel's dimensions:
public class Rect { //... properties public void move(JPanel panel) { int jpWidth = panel.getWidth(); int jpHeight = panel.getHeight(); // rest of the movement logic using jpWidth and jpHeight } }
Another approach is to obtain the Dimension object of the JPanel and pass it to the move() method:
public void move(Dimension dimension) { int jpWidth = dimension.width; int jpHeight = dimension.height; // rest of the movement logic using jpWidth and jpHeight }
Inside the GamePanel class, you can calculate the Dimension object in the paint() method:
public class GamePanel extends JPanel implements Runnable { private Dimension dimension; // rest of the class public void paint(Graphics g) { super.paint(g); dimension = new Dimension(getWidth(), getHeight()); // ... } }
Then, pass the dimension object to the Rect class:
for(Rect rect:rect){ rect.move(dimension); }
The above is the detailed content of How to Accurately Retrieve JPanel Width and Height from an External Class?. For more information, please follow other related articles on the PHP Chinese website!