在随机数游戏中整合按钮的动作监听器

时间:2015-04-29 00:10:03

标签: java random jbutton actionlistener

我对Java比较陌生,我对我写的游戏有疑问。这是一个随机数字游戏,你尝试在最少的猜测中猜测1-10的数字。

我让程序工作,但代码似乎非常低效。就目前而言,我正在为每个数字创建一个JButton,然后为每个按钮创建一个单独的Action Listener,就像这样(为了简单起见省略了很多,因为它与问题无关):

注意: int number =程序选择的随机数,和        int guessCounter =跟踪猜测数量的数字

 public class random extends JFrame{

 //Creating the Buttons

 JButton one = new JButton("1");
 JButton two = new JButton("2");
 JButton three = new JButton("3");

    public static void main(String[] args){

    //Creating Action Listeners

        OneClass uno = new OneClass();
        one.addActionListener(uno);

        TwoClass dos = new TwoClass();
        two.addActionListener(dos);

        ThreeClass tres = new ThreeClass();
        three.addActionListener(tres);

        //Action Listener For Button 1

        private class OneClass implements ActionListener{
            public void actionPerformed(ActionEvent event){
                if(number == 1){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Correct! You guessed the correct number in " + guessCounter + " guesses","Correct!", JOptionPane.PLAIN_MESSAGE);
                }else if(number > 1){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Incorrect. Guess Higher. You have guessed " + guessCounter + " time(s).","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    one.setEnabled(false);
                }else if(number < 1){

                }
            }

        }

        //Action Listener For Button 2

        private class TwoClass implements ActionListener{
            public void actionPerformed(ActionEvent event){
                if(number == 2){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Correct! You guessed the correct number in " + guessCounter + " guesses","Correct!", JOptionPane.PLAIN_MESSAGE);
                }else if(number > 2){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Incorrect. Guess Higher. You have guessed " + guessCounter + " time(s).","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    two.setEnabled(false);
                }else if(number < 2){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null, "Incorrect. Guess Lower. You have guessed " + guessCounter + " time(s)","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    two.setEnabled(false);
                }
            }
        }

        //Action Listener For Button 3

        private class ThreeClass implements ActionListener{
            public void actionPerformed(ActionEvent event){
                if(number == 3){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Correct! You guessed the correct number in " + guessCounter + " guesses","Correct!", JOptionPane.PLAIN_MESSAGE);
                }else if(number > 3){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null,"Incorrect. Guess Higher. You have guessed " + guessCounter + " time(s).","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    three.setEnabled(false);
                }else if(number < 3){
                    guessCounter++;
                    JOptionPane.showMessageDialog(null, "Incorrect. Guess Lower. You have guessed " + guessCounter + " time(s)","Incorrect", JOptionPane.PLAIN_MESSAGE);
                    three.setEnabled(false);
                }
            }

当每个动作监听器都很长时,可以看到效率低下的地方。 我的问题是,是否可以压缩它(即使每个按钮的动作监听器要求将随机数与不同的数字进行比较)?这已经很长了,并且会变得非常长一旦我开始添加更多难度级别,可以选择更多数字。

1 个答案:

答案 0 :(得分:1)

Yes, you can write a listener that is shared by all buttons. You can then get the "action command" of the listener, which will be the text of your button. You can then convert the String to an actual number using the Integer.parseInt(...) method. Then you can invoke your general logic.

Here is an example of a shared listener that simulates the keys of a calculator:

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

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
//              display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}