随机化 JLabel 的替代解决方案

Alternative solution on randomizing JLabel

所以,我有这个任务,用户只需单击我为他们提供的 JLabel 即可猜出正确的数字。我想做的是生成一个随机数然后使用 if (e.getSource() == random) { } 但它似乎 object 和 int 不是兼容的操作数,我希望有人对此有任何解决方案。

无论如何,这是我所做的事情的源代码,因为我的第一个问题还没有任何解决方案。

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import java.util.Random;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Test123 {

private JFrame frame;

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

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

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    
    Random generator = new Random();
    int num;
    num = generator.nextInt(9) + 1;
    int count = 0;
    
    frame = new JFrame();
    frame.setBounds(100, 100, 405, 195);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    
    JLabel NO1 = new JLabel("1");
    NO1.setBounds(20, -26, 43, 183);
    NO1.setFont(new Font("Arial", Font.BOLD, 75));
    frame.getContentPane().add(NO1);
    
    JLabel NO2 = new JLabel("2");
    NO2.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO2.setFont(new Font("Arial", Font.BOLD, 75));
    NO2.setBounds(60, -26, 43, 183);
    frame.getContentPane().add(NO2);
    
    JLabel NO3 = new JLabel("3");
    NO3.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO3.setFont(new Font("Arial", Font.BOLD, 75));
    NO3.setBounds(102, -26, 43, 183);
    frame.getContentPane().add(NO3);
    
    JLabel NO4 = new JLabel("4");
    NO4.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO4.setFont(new Font("Arial", Font.BOLD, 75));
    NO4.setBounds(143, -26, 43, 183);
    frame.getContentPane().add(NO4);
    
    JLabel NO5 = new JLabel("5");
    NO5.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO5.setFont(new Font("Arial", Font.BOLD, 75));
    NO5.setBounds(184, -26, 43, 183);
    frame.getContentPane().add(NO5);
    
    JLabel NO6 = new JLabel("6");
    NO6.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO6.setFont(new Font("Arial", Font.BOLD, 75));
    NO6.setBounds(223, -26, 43, 183);
    frame.getContentPane().add(NO6);
    
    JLabel NO7 = new JLabel("7");
    NO7.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO7.setFont(new Font("Arial", Font.BOLD, 75));
    NO7.setBounds(264, -26, 43, 183);
    frame.getContentPane().add(NO7);
    
    JLabel NO8 = new JLabel("8");
    NO8.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO8.setFont(new Font("Arial", Font.BOLD, 75));
    NO8.setBounds(304, -26, 43, 183);
    frame.getContentPane().add(NO8);
    
    JLabel NO9 = new JLabel("9");
    NO9.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });
    NO9.setFont(new Font("Arial", Font.BOLD, 75));
    NO9.setBounds(345, -26, 43, 183);
    frame.getContentPane().add(NO9);
    
    JLabel CorrectAns = new JLabel("Correct!");
    CorrectAns.setEnabled(false);
    CorrectAns.setBounds(181, 132, 46, 14);
    frame.getContentPane().add(CorrectAns);
    
    NO1.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getSource() == num) {
                count++;
                CorrectAns.setText("Correct!" + count + " attempts");
            }
        }
    });
}
}

MouseEvent#getSource 将 return 触发事件的对象,在您的情况下,JLabel.

“通常”更好的解决方案可能是使用 JButton,然后利用 ActionListener。我会将一个 ActionListener 附加到“正确”按钮以处理正确的工作流程,并将 ActionListener 附加到其他按钮以处理不正确的状态

有关详细信息,请参阅 How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener

import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Twst {
    public static void main(String[] args) {
        new Twst();
    }

    public Twst() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            randomButtons();
        }

        protected void randomButtons() {
            removeAll();
            List<JButton> buttons = new ArrayList<>(4);
            Random rnd = new Random();
            Set<Integer> numbers = new HashSet<>();
            while (numbers.size() < 4) {
                int number = rnd.nextInt(99) + 1;
                numbers.add(number);
            }

            for (Integer number : numbers) {
                JButton btn = new JButton(Integer.toString(number));
                add(btn);
                buttons.add(btn);
            }

            Collections.shuffle(buttons);
            JButton correct = buttons.remove(0);
            correct.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    JOptionPane.showMessageDialog(TestPane.this, "Correct");
                    randomButtons();
                }
            });

            ActionListener wrong = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent evt) {
                    if (evt.getSource() instanceof JButton) {
                        JButton btn = (JButton) evt.getSource();
                        btn.setEnabled(false);
                    }
                    JOptionPane.showMessageDialog(TestPane.this, "Wrong");
                    // You could keep a counter or do what ever else you
                    // want with a wrong guess
                }
            };
            for (JButton btn : buttons) {
                btn.addActionListener(wrong);
            }
            revalidate();
            repaint();
        }

    }
}