简体   繁体   English

如何在 Java 中的 JFrame 上移动 JPanel?

[英]How can I move a JPanel on a JFrame in Java?

So I want to make a simple pong like game from scratch with java.所以我想用 java 从头开始制作一个简单的类似乒乓球的游戏。 I am currently making the movement of the two paddles.我目前正在移动两个桨。 However, I've got stucked at the very beginning.但是,我一开始就被卡住了。 I am trying to set the starting position of the 2 paddles, but I can not.我正在尝试设置 2 个桨的起始 position,但我不能。 I was trying by setting custom layouts, but later I want to change their positions constantly by moving them of course.我试图通过设置自定义布局,但后来我想通过移动它们来不断改变它们的位置。

I've the following code:我有以下代码:

package com.kristof;
import javax.swing.*;
import java.awt.*;

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame("gEngine");
        Player playerOne = new Player();
        Player playerTwo = new Player();

        frame.add(playerOne.getMyPanel());
        frame.add(playerTwo.getMyPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.RED);
        frame.setSize(1280, 720);
        frame.setResizable(false);
        frame.setVisible(true);
    }

    public static class Player {
        private JPanel myPanel;

        public Player() {
            this.myPanel = new MyPanel();
        }

        public JPanel getMyPanel() {
            return myPanel;
        }

    }

    static class MyPanel extends JPanel {
        public MyPanel() {
            setBackground(Color.BLACK);
        }
        @Override
        public void paintComponent(Graphics g) {
            // let the component be painted "natural"
            super.paintComponent(g);
            // Do custom painting
            g.setColor(Color.WHITE);
            g.fillRect(50, getHeight() / 2, 20, 120);
        }
    }

}

I've already tried changing their positions by calling the setLocation method on their myPanel s, but that did not work.我已经尝试通过在他们的myPanel上调用setLocation方法来改变他们的位置,但这不起作用。

So you created a Player class, but you dont have the position of a player in that class.因此,您创建了一个播放器 class,但在该 class 中没有播放器的 position。

Since the paddles will only be moving up and down we only need methods for changing the y coordinate.由于桨只会上下移动,我们只需要更改 y 坐标的方法。

  static class Player{
    int x;
    int y;

   Player(int x){this.x=x;}

   void moveUp(){y--;}
   void moveDown(){y++;}

   void drawPlayer(Graphics2D g){
       g.fillRect(x,y,40,120);
   }

}

Now in the class that extends JPanel (in your case MyPanel ) we can take our newly created Player class as input (by putting it in the constructor)现在在扩展 JPanel 的 class (在您的情况下MyPanel )中,我们可以将新创建的Player class 作为输入(通过将其放入构造函数中)

We can also create a timer so the frames refresh regularly.我们还可以创建一个计时器,以便帧定期刷新。 By adding players[0].moveDown;通过添加players[0].moveDown; in the clock, the first paddle will move down every frame在时钟中,第一个桨将每帧向下移动

In the paint method we can iterate over the players and display them by using the drawPlayer method in the Player class.在paint方法中,我们可以遍历播放器并使用Player class中的drawPlayer方法显示它们。

 MyPanel(Player[] players) {
        this.players = players;
        setBackground(Color.BLACK);

        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                repaint();
                players[0].moveDown;
            }
        }, 300, 1000 / 60);
    }

 @Override
    public void paint(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.WHITE);

        for(Player p : players){
            p.drawPlayer((Graphics2D) g);
        }
    }

Now to put it all together we just need to create the players when we start the program.现在把它们放在一起,我们只需要在启动程序时创建播放器。

Player[] players = new Player[]{
            new Player(100),
            new Player(1000)
    };
    frame.add(new PongWindow(players));

Here is how the code will look like all together:以下是代码的外观:

 import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.Timer; import java.util.TimerTask; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("gEngine"); Player[] players = new Player[]{ new Player(100), new Player(1000) }; frame.add(new PongWindow(players)); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBackground(Color.RED); frame.setSize(1280, 720); frame.setResizable(false); frame.setVisible(true); } static class Player{ int x; int y; Player(int x){this.x=x;} void moveUp(){y+= -8;} void moveDown(){y+= 8;} void drawPlayer(Graphics2D g){ g.fillRect(x,y,40,120); } } static class PongWindow extends JPanel { //private JPanel panel = new JPanel(); Player[] players; PongWindow(Player[] players) { this.players = players; setBackground(Color.BLACK); new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { repaint(); players[0].moveDown(); } }, 300, 1000 / 60); } @Override public void paint(Graphics g) { super.paintComponent(g); g.setColor(Color.WHITE); for(Player p: players){ p.drawPlayer((Graphics2D) g); } } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM