在使用JFrame和DrawWindows时,我需要帮助不使用暴力

时间:2013-08-13 02:08:27

标签: java swing jframe jpanel brute-force

我正在制作一个基本的Hangman游戏,这是我第一次在Java中使用JFrames和DrawWindows。这就是我的困惑所在:

//这会将我的窗口和面板初始化为全局变量:

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

//这会设置我的窗口并将面板添加到其中:

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

}

//接下来的部分将头部绘制到窗口上:

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);
}
}

现在,当这个人得到第二个不正确的猜测时,我想能够将身体添加到头部。但是,当我尝试添加两者时:

...
    } 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) {
...

它只显示身体,整个头部消失。正因为如此,不幸的是,当我画出身体时,我必须REDRAW头部,你可以想象,当我必须写这10次为简单的水平(包括头部,身体,左臂,右臂,左腿,右腿,大礼帽,管子,领带和一杯白兰地)我的代码变得非常漫长。所以现在我的函数类绘制正文如下所示:( DrawHead加上一些正文代码):

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);
        }
}

任何人都可以帮我弄清楚如何才能更聪明地做到这一点?我无法弄清楚如何在DrawBody中调用DrawHead等等。任何帮助将不胜感激!!

Saludos!

1 个答案:

答案 0 :(得分:2)

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

你基本上有两种选择(你可能还有一些选择,但它们可能基于以下概念......)

一...

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

例如......

enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here enter image description here

当前的问题是,为了正确布局所有组件,您需要能够“隐藏”所需的内容,直到您需要它为止。也就是说,必须首先将每个身体部位面板添加到框架中,然后根据需要将其内容“打开”或“关闭”

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();
        }            
    }
}