如何在mouselistener中添加参数

How to add parameter in mouselistener

我想让JLabel答案在用户按下标签时打印出答案。但是我发现第 104 行没有使用 HanoisFrames 中的 "input"。它一直使用 0 作为 "input" 并打印出“0”。我试着把第 96 行写成 "private class MouseHandler extends HanoisFrames implements MouseListener, MouseMotionListener" 并且我使用了 "super (int)" 但它不起作用。我该怎么办?

package Hanois;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Hanoi {

    private JFrame frame;
    JButton[][] buttons= new JButton[3][3];

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Hanoi window = new Hanoi();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Hanoi() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 901, 696);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        JMenuBar menubar=new JMenuBar();//Menu
        frame.setJMenuBar(menubar);

        JMenu file= new JMenu("File");
        file.setFont(new Font("Segoe UI", Font.PLAIN, 21));
        menubar.add(file);
        JMenuItem exit= new JMenuItem("Exit");//provide users a way to exit 
        exit.setFont(new Font("Segoe UI", Font.PLAIN, 21));
        file.add(exit);

        class exitaction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
              System.exit(0);
         }

        }
        exit.addActionListener(new exitaction());


        JPanel panelone = new JPanel();
        frame.getContentPane().add(panelone, BorderLayout.CENTER);
        panelone.setBackground(Color.WHITE);
        panelone.setLayout(new GridLayout(3,4,3,3));


        JPanel paneltwo = new JPanel();
        frame.getContentPane().add(paneltwo, BorderLayout.NORTH);
        paneltwo.setBackground(Color.WHITE);


        JLabel lblFunHanoiTower = new JLabel("Fun Hanoi Tower");
        frame.getContentPane().add(paneltwo, BorderLayout.NORTH);
        lblFunHanoiTower.setForeground(Color.BLACK);
        lblFunHanoiTower.setBackground(SystemColor.activeCaption);
        lblFunHanoiTower.setFont(new Font("Viner Hand ITC", Font.PLAIN, 36));
        paneltwo.add(lblFunHanoiTower); 

        ActionListener listener =new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for(int row = 0; row < buttons.length ; row++) {
                    for(int col= 0; col < buttons[0].length ;col++) {
                        if(e.getSource()==buttons[row][col]){
                            buttons[row][col].setBackground(Color.lightGray);
                            HanoisFrames f= new HanoisFrames(((row*3)+(col+3)));
                            f.setVisible(true);//
                        }
                    }
                }
            }

        };


        for(int row = 0; row < buttons.length ; row++) {
            for(int col= 0; col < buttons[0].length ;col++) {
                buttons[row][col] = new JButton("level "+String.valueOf((row*3)+(col+3)-2));
                buttons[row][col].setFont(new Font("Tempus Sans ITC", Font.BOLD, 32));
                buttons[row][col].setBackground(SystemColor.controlHighlight);
                buttons[row][col].setSize(6, 6);
                buttons[row][col].addActionListener(listener);

                panelone.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
                panelone.add(buttons[row][col]);
                }
            }
        }

}







    package Hanois;

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.EmptyBorder;

    public class HanoisFrames extends JFrame {

        private JPanel contentPane;

        private JButton ret ;
        private JButton next;
        private JButton last;
        private JLabel answer;
        private JMenu menu;
        private JButton reset;
        private JLabel move;
        private JPanel panel;
        static int input;
        private JLabel lblLevel;
        boolean showAnswer=false;

        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        HanoisFrames frame = new HanoisFrames(input);
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * Create the frame.
         */
        public HanoisFrames(int input) {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 901, 696);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new BorderLayout(0, 0));
            setContentPane(contentPane);

            MouseHandler handler=new MouseHandler();

            panel = new JPanel();
            contentPane.add(panel, BorderLayout.SOUTH);
            panel.setLayout(new GridLayout(2,3));

            move = new JLabel("   Move");
            panel.add(move);

            reset = new JButton("Reset");
            panel.add(reset);

            answer = new JLabel();
            answer.setHorizontalAlignment(SwingConstants.CENTER);
            panel.add(answer);
            answer.setText("Answer");
            answer.addMouseListener(handler);
            answer.addMouseMotionListener(handler);

            last = new JButton("Last");
            panel.add(last);

            ret = new JButton("Return");
            panel.add(ret);

            next = new JButton("Next");
            panel.add(next);

            lblLevel = new JLabel("LEVEL   "+ String.valueOf(input-2));
            lblLevel.setHorizontalAlignment(SwingConstants.CENTER);
            lblLevel.setFont(new Font("Viner Hand ITC", Font.PLAIN, 36));
            contentPane.add(lblLevel, BorderLayout.NORTH);
        }

        public int hanoiCalculator(int input) {
            if (input==0){
                  return 0;
                }else if (input==1){
                  return 1;
                }else{
                  return 2*(hanoiCalculator(input-1)+1)-1; 
                }

        }

        private class MouseHandler implements MouseListener,MouseMotionListener {

            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mousePressed(MouseEvent e) {
                answer.setText("Answer:   "+String.valueOf(hanoiCalculator(input)).toString());

            }
            @Override
            public void mouseDragged(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mouseMoved(MouseEvent e) {
                // TODO Auto-generated method stub

            }


            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            public void mouseReleased(MouseEvent e) {
                answer.setText("Answer:   ");

            }

        }

    }

这里:

public class HanoisFrames extends JFrame {

    private JPanel contentPane;

    // ...

    private JPanel panel;
    static int input;

您从未在 HanoiFrames 构造函数中设置输入值,因此它仍然是 int 字段的默认值 0。但即使您确实设置了该字段,因为它是静态字段,在任何 HanoiFrames class 都会更改 all HanoiFrames classes 中的值,因此它 cannot 是一个静态字段。

因此,将输入声明更改为 non-static:

public class HanoisFrames extends JFrame {

    private JPanel contentPane;

    private JButton ret;
    //.....
    private JPanel panel;
    private int input;  // private non-static field now

并在构造函数中设置:

public HanoisFrames(int input) {
    this.input = input;

这样每个 HanoisFrames 都会有一个唯一且持久的输入值


侧面推荐:

我建议不要创建然后交换一堆 JFrames。而是将您的代码用于创建 JPanel,然后在需要时使用 CardLayout 交换它们。