Home > Java > javaTutorial > How to Access JPanel Width and Height from an External Class?

How to Access JPanel Width and Height from an External Class?

Susan Sarandon
Release: 2024-12-14 18:25:13
Original
683 people have browsed it

How to Access JPanel Width and Height from an External Class?

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
        }
    }
}
Copy after login

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template