简体   繁体   中英

How to add parameter in mouselistener

I want to make the JLabel answer print out the answer when users press the label. But I found line 104 does not use the "input" from HanoisFrames. It keeps using 0 as "input" and prints out "0". I tried to write line 96 as "private class MouseHandler extends HanoisFrames implements MouseListener, MouseMotionListener" and I used "super (int)" but it does not work. What should I do?

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:   ");

            }

        }

    }

Here:

public class HanoisFrames extends JFrame {

    private JPanel contentPane;

    // ...

    private JPanel panel;
    static int input;

You never set your input value in your HanoiFrames constructor, and so it remains the default value for an int field, 0. But even if you did set the field because it's a static field, any changes made to it in any HanoiFrames class will change the value in all HanoiFrames classes, and so it cannot be a static field.

So, change input declaration to non-static:

public class HanoisFrames extends JFrame {

    private JPanel contentPane;

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

and set it in the constructor:

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

This way each HanoisFrames will have a unique and durable input value


Side Recommendation:

I would advise against creating and then swapping a bunch of JFrames. Instead gear your code towards creating JPanels, and then swap them when needed, using a CardLayout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM