我想让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字段的默认值0。但是即使您确实设置了该字段是因为它是静态字段,但在任何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;


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



侧面建议:

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

09-28 12:14