当前位置: 首页 > 知识库问答 >
问题:

获取类外部JPanel的宽度和高度

富钧
2023-03-14

因此,我创建了一个简单的模拟,其中方块是随机产生的,随机向量和窗口边缘的反弹。

我希望它能考虑到正在调整的窗口大小。因此,如果我将窗口的尺寸从600x600改为1200x600,则新边框的方块将会弹出,而不是600x600。

我尝试执行getWidth()getHeight(),但它将返回0。因此,我将它放在pain()(因为它在window resize中被调用)方法中,并将返回值保存为局部变量。但是我不能从Rect类调用getjpWidth()。

所以基本上我需要的是在Rect类中的move()方法中获得新的窗口维度。

请随时指出任何其他错误和可以做得更好的事情。我是二维编程的新手(学习计算机科学)

应用程序

import javax.swing.*;

public class Application {
    private Application(){
        //create a JFrame window
        JFrame frame = new JFrame("Moving Squares");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //add a JPanel
        GamePanel gamePanel = new GamePanel();
        frame.add(gamePanel);
        //pack the window around the content
        frame.pack();
        //center
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String args[]){
        new Application();
    }
}

GamePanel

import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;

public class GamePanel extends JPanel implements Runnable{
    private int jpWidth=0, jpHeight=0;

    //set JPanel size
    private static final Dimension DESIRED_SIZE = new Dimension(600,600);
    @Override
    public Dimension getPreferredSize(){
        return DESIRED_SIZE;
    }

    //constructor
    GamePanel(){
        Thread t = new Thread(this);
        t.start();
    }

    private ArrayList <Rect> rect=new ArrayList<>();
    public void run(){
        for(int i=0; i<15; i++){
            rect.add(new Rect());
        }
        while(true){
            for(Rect rect:rect){
                rect.move();
            }
            //repaint still image for better frames
            //should be 100fps instead it's >144fps
            repaint();
            try{Thread.sleep(10);}
            catch(InterruptedException e){/**/};
            repaint();
            try{Thread.sleep(10);}
            catch(InterruptedException e){/**/};
            repaint();
            try{Thread.sleep(10);}
            catch(InterruptedException e){/**/};
        }
    }

    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g.create();
        jpWidth=getWidth();
        jpHeight=getHeight();
        g2d.setColor(Color.white);
        g2d.fillRect(0,0,jpWidth,jpHeight);
        for(Rect rect:rect) {
            g2d.setColor(Color.black);
            g2d.fillRect(rect.getXcord()-1, rect.getYcord()-1, rect.getWidth()+2, rect.getHeight()+2);
            g2d.setColor(Color.getHSBColor(rect.getR(), rect.getG(), rect.getB()));
            g2d.fillRect(rect.getXcord(), rect.getYcord(), rect.getWidth(), rect.getHeight());
        }
    }

    public int getJpWidth() {
        return jpWidth;
    }

    public int getJpHeight() {
        return jpHeight;
    }
}

直肠

import java.util.Random;

public class Rect {
    //properties
    private int width=30, height=30;
    private int R, G, B;
    //movement
    private int xCord, yCord;
    private int xVector, yVector;
    private int xSlope, ySlope;

    public Rect(){
        Random rand = new Random();
        //random color
        R=rand.nextInt(255);
        G=rand.nextInt(255);
        B=rand.nextInt(255);

        //random spawn position
        xCord=rand.nextInt(600-width);
        yCord=rand.nextInt(600-height);

        //direction
        do{
            xVector=rand.nextInt(3) - 1;
            yVector=rand.nextInt(3) - 1;
        }while(xVector==0 || yVector==0);

        //slope
        do{
            xSlope=rand.nextInt(3);
            ySlope=rand.nextInt(3);
        }while(xSlope==0 || ySlope==0);
        xVector*=xSlope;
        yVector*=ySlope;
    }

    public void move(){
        //if(xCord>=//how to get screen width ? ){}
        if((xCord>=600-width) || (xCord<=0)){
            bounceX();
        }
        if((yCord>=600-height) || (yCord<=0)) {
            bounceY();
        }
        xCord+=xVector;
        yCord+=yVector;
    }

    public void bounceX(){
        xVector*=-1;
    }

    public void bounceY(){
        yVector*=-1;
    }

    public int getR() {
        return R;
    }

    public int getG() {
        return G;
    }

    public int getB() {
        return B;
    }

    public int getXcord() {
        return xCord;
    }

    public int getYcord() {
        return yCord;
    }

    public int getWidth(){
        return width;
    }

    public int getHeight(){
        return height;
    }
}

共有1个答案

巫马嘉祯
2023-03-14

所以基本上我需要的是在Rect类中的move()方法中获得新的窗口维度

我不知道它是否是最好的设计,但我将“panel”作为参数传递给“move()”方法,以便可以使用它的宽度/高度。

下面是我手边的一些旧代码,它展示了这种方法:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;

public class BallAnimation4
{
    private static void createAndShowUI()
    {
        BallPanel panel = new BallPanel();

        JFrame frame = new JFrame("BallAnimation4");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( panel );
        frame.setSize(800, 600);
        frame.setLocationRelativeTo( null );
        //frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frame.setVisible( true );

        panel.addBalls(5);
        panel.startAnimation();
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

class BallPanel extends JPanel implements ActionListener
{
    private ArrayList<Ball> balls = new ArrayList<Ball>();

    public BallPanel()
    {
        setLayout( null );
        setBackground( Color.BLACK );
    }

    public void addBalls(int ballCount)
    {
        Random random = new Random();

        for (int i = 0; i < ballCount; i++)
        {
            Ball ball = new Ball();
            ball.setRandomColor(true);
            ball.setLocation(random.nextInt(getWidth()), random.nextInt(getHeight()));
            ball.setMoveRate(32, 32, 1, 1, true);
            ball.setSize(32, 32);
            balls.add( ball );
        }
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        for (Ball ball: balls)
        {
            ball.draw(g);
        }
    }

    public void startAnimation()
    {
        Timer timer = new Timer(75, this);
        timer.start();
    }

    public void actionPerformed(ActionEvent e)
    {
        move();
        repaint();
    }

    private void move()
    {
        for (Ball ball : balls)
        {
            ball.move(this);
        }
    }


    class Ball
    {
        public Color color = Color.BLACK;

        public int x = 0;
        public int y = 0;
        public int width  = 1;
        public int height = 1;

        private int moveX = 1;
        private int moveY = 1;
        private int directionX = 1;
        private int directionY = 1;
        private int xScale = moveX;
        private int yScale = moveY;

        private boolean randomMove = false;
        private boolean randomColor = false;
        private Random myRand = null;

        public Ball()
        {
            myRand = new Random();
            setRandomColor(randomColor);
        }

        public void move(JPanel parent)
        {
            int iRight = parent.getSize().width;
            int iBottom = parent.getSize().height;

            x += 5 + (xScale * directionX);
            y += 5 + (yScale * directionY);

            if (x <= 0)
            {
                x = 0;
                directionX *= (-1);
                xScale = randomMove ? myRand.nextInt(moveX) : moveX;
                if (randomColor) setRandomColor(randomColor);
            }

            if (x >= iRight - width)
            {
                x = iRight - width;
                directionX *= (-1);
                xScale = randomMove ? myRand.nextInt(moveX) : moveX;
                if (randomColor) setRandomColor(randomColor);
            }

            if (y <= 0)
            {
                y = 0;
                directionY *= (-1);
                yScale = randomMove ? myRand.nextInt(moveY) : moveY;
                if (randomColor) setRandomColor(randomColor);
            }

            if (y >= iBottom - height)
            {
                y = iBottom - height;
                directionY *= (-1);
                yScale = randomMove ? myRand.nextInt(moveY) : moveY;
                if (randomColor) setRandomColor(randomColor);
            }
        }

        public void draw(Graphics g)
        {
            g.setColor(color);
            g.fillOval(x, y, width, height);
        }

        public void setColor(Color c)
        {
            color = c;
        }

        public void setLocation(int x, int y)
        {
            this.x = x;
            this.y = y;
        }

        public void setMoveRate(int xMove, int yMove, int xDir, int yDir, boolean randMove)
        {
            this.moveX = xMove;
            this.moveY = yMove;
            directionX  = xDir;
            directionY  = yDir;
            randomMove  = randMove;
        }

        public void setRandomColor(boolean randomColor)
        {
            this.randomColor = randomColor;

            switch (myRand.nextInt(3))
            {
                case 0:  color = Color.BLUE;
                         break;
                case 1:  color = Color.GREEN;
                         break;
                case 2:  color = Color.RED;
                         break;
                default: color = Color.BLACK;
                         break;
            }
        }

        public void setSize(int width, int height)
        {
            this.width  = width;
            this.height = height;
        }
    }

}

另外,请注意,对于动画,您应该使用Swing Timer来调度动画。对Swing组件的更新应该在事件调度线程(EDT)上完成。虽然这个简单的应用程序不太可能导致问题,但确保遵循这个基本规则是一个好习惯,否则您可能会出现随机问题,而且调试随机问题从来都不容易。

 类似资料:
  • 我是JavaFX的新手,我正在编写一个简单的登录应用程序,我想在我的web浏览器中启动它。 我如何获得web浏览器的宽度和高度?是否有一些对象用于此目的,或一个方法,我希望能够调整应用程序的大小,每当浏览器的大小改变。

  • 假设我们有一个垂直的(即flex-direction:column)flexbox容器,具有给定的宽度和高度。flexbox包含div,每个div包含一个图像。 所有DIV和图像都应该以相同的百分比收缩/增长,以填充flexbox的高度,这是通过使用flex-shrink和/或Flex-Grow实现的。 所有图像都应该保持其纵横比(即不拉伸),这是通过不设置其css“width”属性来实现的。 每

  • 请原谅我,如果这是很难遵循,但我有一个具体的问题,我需要帮助解决。我做了大量的研究,尝试了许多解决方案,但都没有奏效。 我的问题是,我有一个类,它正在扩展(下面的代码),这个类需要使用宽度和高度来缩放图像(我正在制作一个程序,用户可以创建自定义教程,包括图像)。当我实例化这个时,我得到一个错误,说宽度和高度必须非零。我明白这是因为布局管理器还没有传递首选大小,但是我不知道如何将该大小传递给面板。在

  • 问题内容: 是否可以在node.js中获取图像的宽度和高度(在服务器端,而不是客户端)?我需要在我正在编写的node.js库中找到图像的宽度和高度。 问题答案: 是的,这是可能的,但是您需要安装GraphicsMagick或ImageMagick。 我都用过,我可以推荐GraphicsMagick,它要快得多。 一旦安装了程序及其模块,就可以执行以下操作来获取宽度和高度。

  • 显然,有两个方法和 是这样的: 我看了这篇文章,但它推荐了一种已弃用的方法: 如何在爪哇fx中获取标签

  • 本文向大家介绍使用Tkinter Python获取屏幕的高度和宽度,包括了使用Tkinter Python获取屏幕的高度和宽度的使用技巧和注意事项,需要的朋友参考一下 Tkinter是为Python程序提供GUI编程功能的库。作为GUI创建的一部分,我们需要创建不同大小和深度的屏幕布局。在此程序中,我们将看到如何以像素和毫米为单位计算屏幕尺寸。我们还可以获得以像素为单位的屏幕深度。作为Tkinte