繁体   English   中英

如何在mouselistener中添加参数

[英]How to add parameter in mouselistener

当用户按下标签时,我想让JLabel答案打印出答案。 但我发现104行不使用HanoisFrames的“输入”。 它一直使用0作为“输入”并打印出“0”。 我试着写第96行作为“私有类MouseHandler扩展HanoisFrames实现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字段的默认值,但是即使你设置了字段因为它是一个静态字段,任何HanoiFrames类中对它所做的任何更改都会改变所有 HanoiFrames类中的值,因此它不能是静态字段。

因此,将输入声明更改为非静态:

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;

这样,每个HanoisFrame都将具有独特且持久的输入值


附加建议:

我建议不要创建然后交换一堆JFrame。 而是将代码设置为创建JPanels,然后在需要时使用CardLayout交换它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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