Java ActionListener 不工作但没有错误

Java ActionListener not working but no errors

所以,上个月我一直在努力学习如何使用 WindowBuilder。我观看了一些 YouTube 视频,尤其是关于 CardLayout 的视频,但我的按钮似乎没有改变面板。

我实际上是想做一个可运行的游戏,但由于我不知道从哪里开始,所以我决定先编写更改面板的部分。(有人告诉我我的代码不完全是适合玩游戏)

我希望面板在玩家点击“新游戏”时发生变化。一开始它给了我错误,但经过几次更改后,它甚至没有给出错误。 所以这是我的代码:

package halma.views;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.Color;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
 

public class MainFrame extends JFrame {

    private JPanel contentPane;
    private JPanel returnBar_panel;
    private JPanel gameBar_panel;
    private JPanel startupReturnBar_Panel;
    private JPanel returnGame_Panel;
    private JPanel gameGUI_Panel;
    private JPanel startupGameBar_Panel;
    private JButton playButton;
    private JButton highScoresButton;
    private JButton exitButton;
    private JPanel resumeReturn_Panel;
    
    static ActionListeners action = new ActionListeners();

    
    CardLayout cardLayout1;  //Used for the buttons' actionlistener.
    CardLayout cardLayout2;
    
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        
        
    }

    //The constructor method.
    public MainFrame() {
        createFrame();
        
        cardLayout1 = (CardLayout)(returnBar_panel.getLayout());
        cardLayout2 = (CardLayout)(gameBar_panel.getLayout());
    }
    
    
    
    //The getters and setters that are required for other classes to use the private variables in the "MainFrame" class.
    
    public JButton getPlayButton() {
        return playButton;
    }

    public JPanel getReturnBar_panel() {
        return returnBar_panel;
    }

    public void setReturnBar_panel(JPanel returnBar_panel) {
        this.returnBar_panel = returnBar_panel;
    }

    public JPanel getReturnGame_Panel() {
        return returnGame_Panel;
    }

    public void setReturnGame_Panel(JPanel returnGame_Panel) {
        this.returnGame_Panel = returnGame_Panel;
    }

    public JPanel getGameGUI_Panel() {
        return gameGUI_Panel;
    }

    public void setGameGUI_Panel(JPanel gameGUI_Panel) {
        this.gameGUI_Panel = gameGUI_Panel;
    }

    public void setPlayButton(JButton playButton) {
        this.playButton = playButton;
    }

    public JPanel getResumeReturn_Panel() {
        return resumeReturn_Panel;
    }

    public void setResumeReturn_Panel(JPanel resumeReturn_Panel) {
        this.resumeReturn_Panel = resumeReturn_Panel;
    }

    
    
    //Runs the game.
    public static void runGame() {
        
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    
    
    //Creating the frame.
    
    public void createFrame() {
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 527, 374);
        setSize(800, 600);
        contentPane = new JPanel();
        contentPane.setBackground(new Color(255, 192, 203));
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        
        returnBar_panel = new JPanel();
        returnBar_panel.setBackground(new Color(255, 192, 203));
        
        gameBar_panel = new JPanel();
        gameBar_panel.setBackground(new Color(255, 192, 203));
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(returnBar_panel, GroupLayout.PREFERRED_SIZE, 155, GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(ComponentPlacement.RELATED)
                    .addComponent(gameBar_panel, GroupLayout.DEFAULT_SIZE, 603, Short.MAX_VALUE)
                    .addContainerGap())
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addComponent(returnBar_panel, GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
                .addComponent(gameBar_panel, GroupLayout.DEFAULT_SIZE, 551, Short.MAX_VALUE)
        );
        gameBar_panel.setLayout(new CardLayout(0, 0));
        
        startupGameBar_Panel = new JPanel();
        
        startupGameBar_Panel.setBackground(new Color(255, 192, 203));
        gameBar_panel.add(startupGameBar_Panel, "name_328512842567600");
        
        playButton = new JButton("New Game");
        playButton.setFocusable(false);
        playButton.setBackground(new Color(255, 160, 122));
        playButton.setForeground(new Color(0, 0, 0));
        playButton.setFont(new Font("Comic Sans MS", Font.ITALIC, 12));
        playButton.addActionListener(action);
        
        
        highScoresButton = new JButton("Records");
        highScoresButton.setForeground(new Color(0, 0, 0));
        highScoresButton.setFocusable(false);
        highScoresButton.setFont(new Font("Comic Sans MS", Font.ITALIC, 12));
        highScoresButton.setBackground(new Color(255, 160, 122));
        
        exitButton = new JButton("Exit");
        exitButton.setForeground(new Color(0, 0, 0));
        exitButton.setFocusable(false);
        exitButton.setFont(new Font("Comic Sans MS", Font.ITALIC, 12));
        exitButton.setBackground(new Color(255, 160, 122));
        GroupLayout gl_startupGameBar_Panel = new GroupLayout(startupGameBar_Panel);
        gl_startupGameBar_Panel.setHorizontalGroup(
            gl_startupGameBar_Panel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_startupGameBar_Panel.createSequentialGroup()
                    .addContainerGap(490, Short.MAX_VALUE)
                    .addGroup(gl_startupGameBar_Panel.createParallelGroup(Alignment.TRAILING, false)
                        .addComponent(exitButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(highScoresButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(playButton, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(24))
        );
        gl_startupGameBar_Panel.setVerticalGroup(
            gl_startupGameBar_Panel.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_startupGameBar_Panel.createSequentialGroup()
                    .addContainerGap(341, Short.MAX_VALUE)
                    .addComponent(playButton)
                    .addGap(18)
                    .addComponent(highScoresButton)
                    .addGap(18)
                    .addComponent(exitButton)
                    .addGap(105))
        );
        startupGameBar_Panel.setLayout(gl_startupGameBar_Panel);
        
        gameGUI_Panel = new JPanel();
        gameGUI_Panel.setBackground(Color.RED);
        gameBar_panel.add(gameGUI_Panel, "name_328347141657400");
        gameGUI_Panel.setLayout(new CardLayout(0, 0));
        returnBar_panel.setLayout(new CardLayout(0, 0));
        
        setStartupReturnBar_Panel(new JPanel());
        getStartupReturnBar_Panel().setBackground(new Color(255, 192, 203));
        returnBar_panel.add(getStartupReturnBar_Panel(), "name_328000881526100");
        
        returnGame_Panel = new JPanel();
        returnGame_Panel.setBackground(new Color(255, 192, 203));
        returnBar_panel.add(returnGame_Panel, "name_328006822278900");
        
        resumeReturn_Panel = new JPanel();
        resumeReturn_Panel.setBackground(Color.PINK);
        returnBar_panel.add(resumeReturn_Panel, "name_331156929215800");
        resumeReturn_Panel.setLayout(new CardLayout(0, 0));
        JPanel panel2 = new JPanel();
        contentPane.setLayout(gl_contentPane);
    }

    public JPanel getStartupReturnBar_Panel() {
        return startupReturnBar_Panel;
    }

    public void setStartupReturnBar_Panel(JPanel startupReturnBar_Panel) {
        this.startupReturnBar_Panel = startupReturnBar_Panel;
    }




package halma.views;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionListeners extends MainFrame implements ActionListener {
    /**
     * 
     */
    private static final long serialVersionUID = 814839576128286295L;
    MainFrame frame = new MainFrame();
    
    public ActionListeners() {
        
        frame.runGame();
        
        
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("meow!");
        frame.cardLayout1.show(frame.getReturnBar_panel(), "resumeReturn_Panel");

        if(e.getSource() == frame.getPlayButton()) {
            System.out.println("T");
            frame.cardLayout1.show(frame.getReturnBar_panel(), "resumeReturn_Panel");
            frame.cardLayout2.show(frame.getGameGUI_Panel(), "Playing");
        }
    }
}

在第二个 class 中,打印了“Meow”一词,但即使我将它从 if-statement 中取出,面板也没有改变。字母 T 没有打印出来。

为什么你想让 ActionListener 有一个 FrameFrame 有一个 ActionListener 不是更有意义吗?即使一个框架有一个动作监听器也没有什么意义。您希望接收用户操作的组件(源对象)包含侦听器。例如,如果用户单击一个按钮,您希望该按钮对用户发起的 操作 作出反应。例如,如果你有一个按钮,当用户点击它时应该在控制台中显示“hello”,你可以这样做:

helloBtn.addActionListener(listener);

然后,您的听众应该看起来像这样:

public class HelloMsgListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Hello!");
    }
}

当您的侦听器如此简单时,将其添加为匿名实体可能更有意义。

你写的代码很乱。您创建了一个具有框架的侦听器,但该框架不是具有包含具有该框架的侦听器的组件的实例。

解决此问题的方法是创建一个 class 来创建框架并运行您的应用程序

public class MyApp {
    
    public static void main (String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            
            @Override
            public void run () {
                createAndShowGUI();
            }

            private void createAndShowGUI () {
                JFrame frame = new JFrame();
                ...
                frame.setVisible(true);
                // Create the rest of the components and add to frame
                playButton.addActionListener(new ActionListener() {
                
                    @Override
                    public void actionPerformed (ActionEvent e) {
                        System.out.println("meow!");
                        frame.cardLayout1.show(frame.getReturnBar_panel(),
                            "resumeReturn_Panel");
                    
                        if (e.getSource() == frame.getPlayButton()) {
                            System.out.println("T");
                            frame.cardLayout1.show(frame.getReturnBar_panel(),
                                "resumeReturn_Panel");
                            frame.cardLayout2.show(frame.getGameGUI_Panel(), "Playing");
                        }
                    }
                });
            }
        });
    }
}

然后,您创建按钮