0

I am making a basic Hangman game and this is my first time using JFrames and DrawWindows in Java. Here is where my confusion lies:

//This initializes my window and a panel as global variables:

JFrame window = new JFrame("Let's play hangman!");
DrawWindow panel = new DrawWindow();

//This sets up my window and adds the panel to it:

public HangmanTwo() {
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setBackground(Color.white);
    window.setSize(500, 500);
    window.add(panel);
    window.setVisible(true);

}

//This next parts draws the head onto the window:

public class DrawWindow extends JPanel {
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.black);
    g.drawRect(50, 50, 75, 400);
    g.setColor(Color.lightGray);
    g.fillRect(50, 50, 75, 400);
    g.drawRect(100, 50, 150, 50);
    g.fillRect(100, 50, 250, 50);


    //Draws noose and head
    g.setColor(Color.black);
    g.fillRect(250, 100, 1, 75);
    g.drawOval(220, 175, 60, 60);
    g.fillOval(220, 175, 60, 60);
}
}

Now, when the person gets their second incorrect guess, I wanted to just be able to add the body onto the head. However, when I try to add both on:

...
    } else if (score == 2) {
        printOutScore(2, 4);
        DrawHead head = new DrawHead();
        DrawBody body = new DrawBody();
        window.add(head);
        window.add(body);
        window.setVisible(true);
    } else if (score == 3) {
...

It only shows the body and the whole head disappears. Because of this, unfortunately, when I draw the body, I have to REDRAW the head, which you can imagine, when I have to write this 10 times for the easy level (which includes head, body, left arm, right arm, left leg, right leg, top hat, pipe, tie, and a shot of brandy) my code is getting ridiculously long. So now my function class to draw the body looks like this: (the DrawHead plus some body code):

public class DrawBody extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        /*Draws wood structure to start
        g.setColor(Color.black);
        g.drawRect(50, 50, 75, 400);
        g.setColor(Color.lightGray);
        g.fillRect(50, 50, 75, 400);
        g.drawRect(100, 50, 150, 50);
        g.fillRect(100, 50, 250, 50);

        //Draws noose and head
        g.setColor(Color.black);
        g.fillRect(250, 100, 1, 75);
        g.drawOval(220, 175, 60, 60);
        g.fillOval(220, 175, 60, 60);

        //Draws body
        g.drawRect(245, 235, 10, 120);
        g.fillRect(245, 235, 10, 120);
        }
}

Can anyone please help me figure out how I could do it smarter? I can't figure out how to just call DrawHead in DrawBody and so on. Any help would be much appreciated!!

Saludos!

4

1 回答 1

2

您遇到的基本问题JFrame是使用 a的事实BorderLayout,默认情况下,它只允许单个组件占据五个可能的布局位置中的每一个。这意味着,当您将新组件添加到默认位置时,曾经存在的组件会“隐藏”

您基本上有两个选择(您可能还有更多选择,但它们可能基于以下概念......)

一...

您可以使用不同的布局管理器并在其自己的面板上绘制每个身体部位......

例如...

在此处输入图像描述在此处输入图像描述在此处输入图像描述在此处输入图像描述在此处输入图像描述在此处输入图像描述在此处输入图像描述

直接的问题是,为了正确布局所有组件,您需要能够“隐藏”已绘制的内容,直到您需要它为止。即每个body part面板必须先添加到frame中,然后根据需要将其内容“打开”或“关闭”

import java.awt.BorderLayout;
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.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class HangMan03 {

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

    public HangMan03() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new GallosPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class GallosPane extends JPanel {

        private HeadPane headPane;
        private BodyPane bodyPane;
        private ArmPane rightArm;
        private ArmPane leftArm;
        private LegPane rightLeg;
        private LegPane leftLeg;

        private int score = 0;

        public GallosPane() {
            setLayout(new BorderLayout());
            JPanel personPane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.SOUTH;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            headPane = new HeadPane();
            personPane.add(headPane, gbc);

            gbc.fill = GridBagConstraints.NONE;
            gbc.gridwidth = 1;
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.anchor = GridBagConstraints.NORTHEAST;
            rightArm = new ArmPane(Side.Right);
            personPane.add(rightArm, gbc);

            gbc.gridx = 1;
            gbc.anchor = GridBagConstraints.NORTH;
            bodyPane = new BodyPane();
            personPane.add(bodyPane, gbc);

            gbc.gridx = 2;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            leftArm = new ArmPane(Side.Left);
            personPane.add(leftArm, gbc);

            gbc.gridx = 0;
            gbc.gridy = 2;
            gbc.anchor = GridBagConstraints.NORTHEAST;
            rightLeg = new LegPane(Side.Right);
            personPane.add(rightLeg, gbc);

            gbc.gridx = 2;
            gbc.anchor = GridBagConstraints.NORTHWEST;
            leftLeg = new LegPane(Side.Left);
            personPane.add(leftLeg, gbc);

            add(personPane);

            JButton btn = new JButton("Next");
            add(btn, BorderLayout.SOUTH);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    score++;
                    if (score == 1) {
                        headPane.setPainted(true);
                    } else if (score == 2) {
                        leftArm.setPainted(true);
                    } else if (score == 3) {
                        rightArm.setPainted(true);
                    } else if (score == 4) {
                        bodyPane.setPainted(true);
                    } else if (score == 5) {
                        leftLeg.setPainted(true);
                    } else if (score == 6) {
                        rightLeg.setPainted(true);
                    } else {
                        headPane.setPainted(false);
                        leftArm.setPainted(false);
                        rightArm.setPainted(false);
                        bodyPane.setPainted(false);
                        leftLeg.setPainted(false);
                        rightLeg.setPainted(false);
                        score = 0;
                    }
                }
            });

        }

    }

    public enum Side {

        Left, Right;
    }

    public static class PartPane extends JPanel {

        private boolean painted;

        public PartPane() {
            setOpaque(false);
        }

        public void setPainted(boolean painted) {
            this.painted = painted;
            repaint();
        }

        public boolean isPainted() {
            return painted;
        }

    }

    public static class HeadPane extends PartPane {

        public static final int RADIUS = 10;

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isPainted()) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x = (getWidth() - RADIUS) / 2;
                int y = (getHeight() - RADIUS) / 2;
                g2d.drawOval(x, y, RADIUS - 1, RADIUS - 1);
                g2d.dispose();
            }
        }

    }

    public static class BodyPane extends PartPane {

        public BodyPane() {
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(1, HeadPane.RADIUS * 2);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isPainted()) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.fillRect(0, 0, getWidth(), getHeight());
                g2d.dispose();
            }
        }

    }

    public static class ArmPane extends PartPane {

        private Side side;

        public ArmPane(Side side) {
            super();
            this.side = side;
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(HeadPane.RADIUS, HeadPane.RADIUS);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (isPainted()) {
                Graphics2D g2d = (Graphics2D) g.create();
                int x1 = 0;
                int y1 = 0;
                int x2 = 0;
                int y2 = 0;

                switch (side) {
                    case Left:
                        x2 = getWidth() - 1;
                        y2 = getHeight() - 1;
                        break;
                    case Right:
                        x1 = getWidth() - 1;
                        y1 = 0;
                        y2 = getHeight() - 1;
                        break;
                }

                g2d.drawLine(x1, y1, x2, y2);
                g2d.dispose();
            }
        }

    }

    public static class LegPane extends ArmPane {

        public LegPane(Side side) {
            super(side);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(HeadPane.RADIUS, HeadPane.RADIUS * 2);
        }

    }

}

现在,在我看来,这是非常复杂的,充满了问题并且很容易被破坏......

您可以使用单个组件并直接对其进行绘制。

到目前为止,这是一种更简单的方法,因为您可以完全控制每个部分的渲染方式。

import java.awt.BorderLayout;
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.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class HangMan031 {

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

    public HangMan031() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new GallosPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class GallosPane extends JPanel {

        private PersonPane personPane;

        private int score = 0;

        public GallosPane() {
            setLayout(new BorderLayout());

            personPane = new PersonPane();
            add(personPane);

            JButton btn = new JButton("Next");
            add(btn, BorderLayout.SOUTH);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    personPane.badGuess();
                }
            });

        }

    }

    public static class PersonPane extends JPanel {

        public static final int RADIUS = 10;
        public static final int HEAD_HEIGHT = RADIUS;
        public static final int BODY_HEIGHT = HEAD_HEIGHT * 2;
        public static final int ARM_HEIGHT = HEAD_HEIGHT;
        public static final int ARM_WIDTH = RADIUS;
        public static final int LEG_HEIGHT = HEAD_HEIGHT * 2;
        public static final int LEG_WIDTH = RADIUS;
        private int score = 0;

        public PersonPane() {
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(((ARM_WIDTH + LEG_WIDTH) * 2) + 1, HEAD_HEIGHT + BODY_HEIGHT + LEG_HEIGHT);
        }

        public void badGuess() {
            score++;
            if (score > 6) {
                score = 0;
            }
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            Dimension size = getPreferredSize();

            int centerX = getWidth() / 2;
            int y = ((getHeight() - (size.height)) / 2);


            switch (score) {
                case 6:
                    int x = centerX;
                    int yPos = y + HEAD_HEIGHT + BODY_HEIGHT;
                    g2d.drawLine(x, yPos, x - LEG_WIDTH, yPos + LEG_HEIGHT);
                case 5:
                    x = centerX;
                    yPos = y + HEAD_HEIGHT + BODY_HEIGHT;
                    g2d.drawLine(x, yPos, x + LEG_WIDTH, yPos + LEG_HEIGHT);
                case 4:
                    x = centerX;
                    yPos = y + HEAD_HEIGHT;
                    g2d.drawLine(x, yPos, x, yPos + BODY_HEIGHT);
                case 3:
                    x = centerX;
                    yPos = y + HEAD_HEIGHT;
                    g2d.drawLine(x, yPos, x - ARM_WIDTH, yPos + ARM_HEIGHT);
                case 2:
                    x = centerX;
                    yPos = y + HEAD_HEIGHT;
                    g2d.drawLine(x, yPos, x + ARM_WIDTH, yPos + ARM_HEIGHT);
                case 1:
                    x = centerX - (HEAD_HEIGHT / 2);
                    yPos = y;
                    g2d.drawOval(x, y, HEAD_HEIGHT, HEAD_HEIGHT);
                case 0:
                    break;
            }
            g2d.dispose();
        }            
    }
}
于 2013-08-13T03:09:43.237 回答