简体   繁体   中英

How to create a rectangle in Java Swing

Am very lost on how to make a rectangle or object that can be seen in the panel. Currently have the below code but is only giving a background color. I am unsure how to call the paintComponent method or the repaint in this scenario.

public class myProject extends JPanel {

    public final int WIDTH= 1000, HEIGHT= 1000;
    public Rectangle user;
    public static myProject myProject;

    public static void main(String[] args) {
        myProject= new myProject();
        myProject.start();

    }

    public void start() {
        JFrame main= new JFrame("Main");
        JPanel game= new JPanel();
        main.add(game);
        main.setSize(WIDTH, HEIGHT);
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setVisible(true);

        JLabel welcome= new JLabel("Welcome");
        welcome.setSize(new Dimension(50, 50));
        welcome.
        game.add(welcome, BorderLayout.NORTH);
        game.setBackground(Color.BLACK);

        JButton startButton= new JButton("Start");
        startButton.setFont(startButton.getFont().deriveFont(20.0f));

        startButton.setLayout(new BorderLayout());

        startButton.addActionListener((ActionEvent ae) -> startClicked());
        game.add(startButton, BorderLayout.CENTER);
        startButton.setVisible(true);

    }

    public void repaint(Graphics g) {
        // TODO Auto-generated method stub

        g.setColor(Color.green);
        g.fillRect(0, HEIGHT - 50, WIDTH, 50);

        g.setColor(Color.red);
        g.fillRect(user.x, user.y, user.width, user.height);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.drawRect(10, 10, 150, 40);
    }

    public void startClicked() {
        System.out.println("Game Started");
        repaint();
    }

}

I am unsure how to call the paintComponent method

You don't. The paint sub system will call your component's "paint" methods when it decides something needs to be update, this is a passive update workflow, as a paint pass may be triggered for any number of reasons at any time.

You can request a paint pass by calling repaint on your component, but it's still up to the paint sub system to decide what and when a paint pass will take place. repaint(Graphics g) is badly named, however, you'd have to call it from within the paintComponent method.

I would recommend looking at Painting in AWT and Swing and Performing Custom Painting for more details about how paint works and how you should work with.

You might also like to have a look at How to Use CardLayout for switching between views.

The following example uses a Overlayout so that I can "overlay" the menu over the top the game, and basically acts as a "pause" like state.

It makes use of a "delegate" to allow the menu/game change the state accordingly, but without actually needing to know about each other.

It makes use ofSwing Timer to animate the position of the box across the screen. The nice thing about this is that it can be easily started and stopped

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
import javax.swing.Timer;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new MainPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class MainPane extends JPanel {

        public interface Controller {
            public void startGame();
            public void pauseGame();
        }

        private GamePane gamePane;
        private MenuPane menuPane;
        public MainPane() {
            setLayout(new OverlayLayout(this));

            Controller controller = new Controller() {
                @Override
                public void startGame() {
                    menuPane.setVisible(false);
                    gamePane.start();
                }

                @Override
                public void pauseGame() {
                    menuPane.setVisible(true);
                    gamePane.stop();
                }
            };

            gamePane = new GamePane(controller);
            menuPane= new MenuPane(controller);

            add(menuPane);
            add(gamePane);
        }
    }

    public class MenuPane extends JPanel {
        private MainPane.Controller controller;
        public MenuPane(MainPane.Controller controller) {
            this.controller = controller;
            setOpaque(false);
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            JLabel label = new JLabel("Welcome");
            label.setForeground(Color.WHITE);
            add(label, gbc);

            JButton startButton = new JButton("Start");
            add(startButton, gbc);

            startButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    controller.startGame();
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(new Color(0, 0, 0, 192));
            g.fillRect(0, 0, getWidth(), getHeight());
        }
    }

    public class GamePane extends JPanel {
        private MainPane.Controller controller;
        private Timer timer;
        private Rectangle box = new Rectangle(0, 0, 50, 50);
        public GamePane(MainPane.Controller controller) {
            this.controller = controller;
            setBackground(Color.RED);

            box.y = (800 - box.height) / 2;

            timer = new Timer(5, new ActionListener() {
                private int xDelta = 1;
                @Override
                public void actionPerformed(ActionEvent e) {
                    box.x += xDelta;
                    box.y = (getHeight() - box.height) / 2;
                    if (box.x < 0) {
                        box.x = 0;
                        xDelta *= -1;
                    } else if (box.x + box.width > getWidth()) {
                        box.x = getWidth() - box.width;
                        xDelta *= -1;
                    }
                    repaint();
                }
            });

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    controller.pauseGame();
                }
            });
        }

        public void start() {
            timer.start();
        }

        public void stop() {
            timer.stop();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(800, 800);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.BLUE);
            g2d.fill(box);
            g2d.dispose();
        }

    }
}

Now, obviously, if you want to control more then one object, you will need to maintain the individual states of those objects and access them from something like List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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