Java Swing JButton 未显示在 JPanel 上

标签 java swing jbutton

我正在为家庭作业制作一款塔防游戏。我正在回收作业中的旧代码,在该作业中我必须创建一个海洋,并且我回顾并进行了比较,因此面板应该显示 JButton,并且它之前显示过它们,但现在面板不显示按钮。还有其他类包含此代码,但与 JButton 相关的所有内容都发生在这些类中。

感谢您的帮助。

import javax.swing.JFrame;
import java.awt.BorderLayout; 
public class Td {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Tower Defence");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ControlPanel2 control = new ControlPanel2();
        frame.add(control, BorderLayout.WEST);
        frame.add(new GamePanel(control)); //defaults to CENTER
        frame.pack();
        frame.setVisible(true);
    }
}



    import javax.swing.Box;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;

     public class ControlPanel2 extends JPanel {
        private JButton basicTower, advanceTower, nextWave;
        private JLabel score, money;
        private int x, y;

        private String action;

        public ControlPanel2() {
            setPreferredSize(new Dimension(150, GamePanel.HEIGHT));

            basicTower = new JButton("Basic Tower");
            basicTower.addActionListener(new ButtonListener("BasicTower"));
            this.add(basicTower);

            advanceTower = new JButton("Advance Tower");
            advanceTower.addActionListener(new ButtonListener("advanceTower"));
            add(advanceTower);

            nextWave = new JButton("Next Wave!");
            nextWave.addActionListener(new ButtonListener("nextWave"));
            add(nextWave);
            System.out.println("MADE IT");
            action = "none";
            x = 100;
            y = 1000;
            score = new JLabel ("Score: " + x);
            money = new JLabel ("Money:  " + y);
            add(score);
            add(money);

        }

        public void setY(int z) {
            y = y - z;
            money.setText("Money: " + y);
        }

        public void setX(int z) {
            x = x + z;
            score.setText("Score: " + x);
        }

        public int getY() {
            return y;
        }

        public int getX() {
            return x;
        }

        public String getAction() {
            return action;
        }

        public class ButtonListener implements ActionListener {
            private String name;

            public ButtonListener(String className) {
                name = className;
            }

            public void actionPerformed(ActionEvent e) {
                action = name;
            }
        }
    }




    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import javax.swing.Timer;
    import java.awt.Point;
    import javax.swing.JPanel;
    import java.util.ArrayList;
    import java.lang.reflect.InvocationTargetException; 
    import java.util.Random;

    public class GamePanel extends JPanel{
        public static final int WIDTH = 600, HEIGHT = 600;

        private ArrayList<Cage> cage = new ArrayList<Cage>();
        private ArrayList<Tower> towers = new ArrayList<Tower>();
        private ControlPanel2 cPanel;
        private Timer timer;
        private Rectangle bounds;

        public GamePanel(ControlPanel2 control) {
            //***Does not need to be edited
                cPanel = control;
                setPreferredSize(new Dimension(WIDTH, HEIGHT));
                setBackground(Color.gray);
                bounds = new Rectangle(0, 0, WIDTH, HEIGHT);
                addMouseListener(new ClickListener());
                timer = new Timer(200, new TimerListener());
                timer.start();
            }
        public void paintComponent(Graphics g) {
            //***Does not need to be edited
                super.paintComponent(g); //Call to the super constructor to make sure
                //all of JPanel's paintComponent stuff is called first
                for (Tower a : towers) {
                    a.draw(g);
                }
            }
        private class TimerListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                //INSERT CODE HERE
                //Call the methods in OceanPanel that you think need
                //to be called each time the timer is triggered.
                validate();
                repaint();
            }
        }
        private class ClickListener extends MouseAdapter {
            //***You do not need to edit this private inner class
            // but you should know what it is accomplishing. 
            /**
             * You are not required to know what exactly is going on in this method.
             * However, if you are curious, you should check out the Class API. Using
             * a tool called 'reflection', it is instantiating a Fish given a
             * String that represents the class name. This way, we don't need a long
             * series of 'if' statements to create a certain type of Fish.
             *@param Point p is where the fish will be placed to start.
             *@param String className is the class name for the type of Fish that
             *       we want to instantiate.
             *@return Fish that is exactly the type of Fish that we want to add
             *        to the panel.
             */
             public Tower instantiateTower(Point p, String className) {
                 try {
                     Class cl = Class.forName(className);
                     return (Tower) (cl.getDeclaredConstructor(
                         int.class, int.class, Rectangle.class).newInstance(
                             p.x, p.y, bounds));
                 } catch (ClassNotFoundException e) {
                     e.printStackTrace();
                     System.exit(1);
                 } catch (NoSuchMethodException e) {
                     e.printStackTrace();
                     System.exit(1);
                 } catch (InstantiationException e) {
                     e.printStackTrace();
                     System.exit(1);
                 } catch (IllegalAccessException e) {
                     e.printStackTrace();
                     System.exit(1);
                 } catch (InvocationTargetException e) {
                     e.printStackTrace();
                     System.exit(1);
                 }
                 return null;
             }
             public void mousePressed(MouseEvent e) {
                 //Determine which type of Fish to create by asking ControlPanel
                 //This information is based on the button that was last clicked
//                 String towerType = cPanel.getAction();
                 Point p = e.getPoint();
                 System.out.println(e.getPoint());
                 repaint();
             }
        }
}

最佳答案

您的 ControlPanel2 类是一个扩展 JPanel 的类,它有两个方法:getX()getY(),它们覆盖关键的组件方法,这些方法对组件至关重要放置,并且您的无意覆盖会造成困惑。您将需要更改这些方法的名称。也许您可以重命名变量 xPos 和 yPos,并将方法更改为 getXPos()getYPos()

例如你可以这样做:

 public class ControlPanel2 extends JPanel {
    private JButton basicTower, advanceTower, nextWave;
    private JLabel score, money;

    // note change 
    private int xPos; 
    private int yPos;

    private String action;

    public ControlPanel2() {
        setPreferredSize(new Dimension(150, GamePanel.HEIGHT));

        basicTower = new JButton("Basic Tower");
        basicTower.addActionListener(new ButtonListener("BasicTower"));
        this.add(basicTower);

        advanceTower = new JButton("Advance Tower");
        advanceTower.addActionListener(new ButtonListener("advanceTower"));
        add(advanceTower);

        nextWave = new JButton("Next Wave!");
        nextWave.addActionListener(new ButtonListener("nextWave"));
        add(nextWave);
        System.out.println("MADE IT");
        action = "none";

        // **** note changes. As an aside -- avoid "magic" numbers
        xPos = 100;
        yPos = 1000;

        score = new JLabel ("Score: " + x);
        money = new JLabel ("Money:  " + y);
        add(score);
        add(money);

    }

    public void setYPos(int z) {
        yPos -= z;
        money.setText("Money: " + yPos);
    }

    public void setXPos(int z) {
        xPos += z;
        score.setText("Score: " + xPos);
    }

    public int getYPos() {
        return yPos;
    }

    public int getXPos() {
        return xPos;
    }

请注意,这就是为什么通过组合而不是继承来扩展类通常更好的原因之一——以避免无意的覆盖导致奇怪的副作用。

关于Java Swing JButton 未显示在 JPanel 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320288/

相关文章:

java - ActionListener 不工作 Java

java - 向用户显示 JButton 已开启某些功能

java - onItemClickListener 设置为 null 后如何重置回 true?

java - 进程正在暂停,直到我关闭程序

java - Swing 流布局中断元素

java - jprogressbar 可见并且正在单击按钮

java - JTextField 使用 JButton 输出到新窗口

java - 为什么人们在事件队列上运行 Java GUI

java - java中mysql的Spring数据和hibernate错误

java - 从 Spring MVC - DAO 项目迁移到 Spring Boot