How to Get JPanel Width and Height Outside of the Class
In your code, you're trying to access the JPanel's width and height from the Rect class, which isn't possible as the Rect class is unaware of its containing JPanel. To address this issue, you can pass a reference of the JPanel to the move() method within the Rect class.
Here's how you can modify the code:
GamePanel.java
public class GamePanel extends JPanel implements Runnable{ // ... (same as before) public void move() { for(Rect rect: rect) { rect.move(this); // Passing 'this' reference to the 'move()' method } } }
Rect.java
public class Rect { // ... (same as before) public void move(JPanel panel){ // Now you can access the JPanel's width and height using 'panel' int jpWidth = panel.getWidth(); int jpHeight = panel.getHeight(); // ... (remaining code) } }
With these modifications, the move() method in the Rect class can now access the updated JPanel's width and height, allowing you to adjust the movement of the rectangles based on the current window dimensions.
The above is the detailed content of How to Access JPanel Width and Height from an External Class?. For more information, please follow other related articles on the PHP Chinese website!