Помогите узнать, какая кнопка была нажата - PullRequest
2 голосов
/ 02 апреля 2009
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Random;
/**
 *
 */
public class GUI
{
    private static final int BTN_MAX = 8;


    private JFrame frame;
    private JPanel panel;
    private JPanel scores;
    private JButton[] buttons;
    private ImageIcon[] icons;

    private Random rand;

    private ImageIcon beach;
    private ImageIcon lips;
    private ImageIcon discoball;
    private ImageIcon flowers;
    private ImageIcon blank;




    /**
     *
     */
    public GUI()
    {        
        beach = new ImageIcon("beach.jpg");
        lips = new ImageIcon("lips.jpg");
        discoball = new ImageIcon ("discoball.jpg");
        flowers = new ImageIcon ("flowers.jpg");
        blank = new ImageIcon ("blank.jpg");

        buttons = makeButtons();
        rand = new Random();
        startingCondition();

        icons = new ImageIcon[] { beach, lips, discoball, lips, beach, flowers, discoball, flowers};


        makeFrame();
        makeMenuBar(frame);        
        frame.pack();
        frame.setVisible(true);


    }

    /**
     * Makes the frame for the gui, inclusive of adding all components.
     */
    private void makeFrame()
    {
        int horizGap = 25; // Using this for spaces between the grid layout components
        int vertGap = 25;  // Using this for the spaces between the grid layout componeents

        frame = new JFrame("Noughts and Crosses");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(4,2));//set layout of frame to BorderLayout

        for (int i = 0; i < BTN_MAX; i++){
            contentPane.add(buttons[i]);
        }
    }

    /**
     * 
     */
    private void makeMenuBar(JFrame frame)
    {             
        JMenuBar menubar = new JMenuBar();
        frame.setJMenuBar(menubar);

        JMenu menu;
        JMenuItem item;

        menu = new JMenu("File");
        menubar.add(menu);

        item = new JMenuItem("Reset Entire Game");
            item.addActionListener(new ActionListener() 
            {
               public void actionPerformed(ActionEvent e)
               { 
               }
            });
        menu.add(item);

        item = new JMenuItem("Reset This Game");
            item.addActionListener(new ActionListener() 
            {
               public void actionPerformed(ActionEvent e) 
               { 
               }
            });
        menu.add(item);    

        item = new JMenuItem("Quit");
            item.addActionListener(new ActionListener() 
            {
               public void actionPerformed(ActionEvent e) 
               { 
               }
            });
        menu.add(item);            

        frame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {

            }
        });  

        menu = new JMenu("About");
        menubar.add(menu); 

        item = new JMenuItem("About The Game");
            item.addActionListener(new ActionListener() 
            {
               public void actionPerformed(ActionEvent e) 
               { 
               }
            });
        menu.add(item);
    }    


    /**
     * 
     */
    private JButton[] makeButtons()
    {
        final JButton button[] = new JButton[8];
        for (int i = 0; i < BTN_MAX; i++)
        {
            button[i] = new JButton("");
            button[i].setPreferredSize(new Dimension(200, 100));
            final int tmp = i;
            button[i].addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {  
                    checkForPair();
                    takeGo();
                }
            });
        }
        return button;
    }

    /**
     * 
     */
    private void startingCondition()
    {
        for (int i = 0; i < 8; i++){
            buttons[i].setIcon(blank);
        }
    }


    /**
     * 
     */
    public int returnButtonNumber()
    {
        return 0;
        // need to tell which button in the array has been clicked
        //so i can send a value to the takeGo method
        //appropriatley
    }  

    public ImageIcon getIcon(int number)
    {
        return icons[number];
    }

    /**
     * 
     */
    public boolean checkForPair()
    {
        return false;
    }

    /**
     * 
     */
    public void takeGo()
    {
        int i = returnButtonNumber();

        buttons[i].setIcon(getIcon(i));
    }
}

Привет, мне просто интересно, может ли кто-нибудь помочь мне с методом, чтобы определить, какой номер кнопки был нажат, тогда я могу отправить это значение в другой метод для отображения соответствующего изображения, все идеи приветствуются, хотя могли бы пожалуйста, старайтесь избегать полного кода настолько, насколько это возможно, так как я хочу попробовать сделать это самому, примеры были бы хорошими, хотя

спасибо

Ответы [ 3 ]

3 голосов
/ 02 апреля 2009

Чтобы дать вам как можно меньше информации; -) ... попробуйте посмотреть на JButton.setActionCommand ()

Кроме того, если вы собираетесь использовать один и тот же ActionListener для каждой кнопки и проверять, какая кнопка была нажата, вам следует просто создать экземпляр ActionListener один раз и добавить его к каждой кнопке, а не создавать ее для каждой кнопки.

1 голос
/ 02 апреля 2009

Используйте разные экземпляры ActionListener для каждого отдельного действия. Это вполне может быть тот же класс, построенный возможно с другими вещами в том же параметризованном методе.

Как в:

    addItem("Quit", quitCommand);
...
private void addItem(String text, final Runnable command) {
    JMenuItem item = new JMenuItem(text);
    item.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) { 
            command.run();
        }
    });
    menu.add(item);  
}
1 голос
/ 02 апреля 2009

Вы можете использовать ActionEvent.getSource () в сочетании с вашими кнопками JButton [], чтобы узнать индекс кнопки, которая активировала это действие. Я надеюсь, что это было достаточно загадочно:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...