Как я могу переместить графический элемент на панели Java? - PullRequest
0 голосов
/ 07 октября 2019

Я сейчас работаю над простой игрой в стиле понг, но я застрял с позиционированием прямоугольника. Я хочу изменить его положение Y на половину фактической высоты панели.

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

public class Main {

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


package com.game;

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

public class Player {
    public Player(JFrame frame) {
        MyPanel panel = new MyPanel();
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.BLACK);
        frame.setSize(1280, 720);
        frame.setVisible(true);
    }
}
class MyPanel extends JPanel {
    public void paintComponent(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(50, 60, 20, 120);
    }
}

1 Ответ

1 голос
/ 07 октября 2019

В вашем коде много "проблем". Я предлагаю вам найти какие-то учебники или что-то в этом роде. Вы frame.setVisible(true) и вещи внутри Player конструктора классов. Понимаете ли вы, что каждый раз, когда вы создаете объект Player, все эти вещи будут применяться к JFrame? Это необходимо? Может быть, вы должны сделать их только один раз. Также для paint компонента в соответствии с его положением в соответствии с размером, вы можете выполнить g.fillRect(50, getHeight() / 2, 20, 120);

public class Test {

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

        // Set the proper layout manager
        frame.setLayout(new GridLayout());

        frame.add(playerOne.getMyPanel());
        frame.add(playerTwo.getMyPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBackground(Color.BLACK);
        frame.setSize(1280, 720);
        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 {
        @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);
        }
    }

}

Edit (на основе комментария):

Фон по умолчаниюпотому что GridLayout разбивает экран на 2 панели (в середине кадра). Даже рамка имеет BLACK фон, эти две панели закрывают ее. Таким образом, фон, который вы видите, исходит от панелей, а не от рамки. Чтобы изменить его, вам нужно изменить фон панелей (и сделать их непрозрачными):

static class MyPanel extends JPanel {
    public MyPanel() {
        super();
        setOpaque(true);
        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);
    }
}
...