как остановить ActionListener от запоминания предыдущих событий - PullRequest
3 голосов
/ 28 марта 2012

Я только новичок в Java.Я пытаюсь заполнить сетку 6x6 6 разными цветами, не используя тот же цвет, который появляется в той же строке или столбце.в моем коде я установил сетку JButton 6x6, хранящуюся в массиве, называемом кнопками.когда я нажимаю одну из этих кнопок JButtons, создается сетка JButtons 6x1, называемая paintBox.JButton в paintBox объявляются в верхней части программы как fillRed, fillYellow и т.д., когда я нажимаю fillRed, он устанавливает обратный раунд JButton из сетки 6x6 красным, но когда я нажимаю другой JButton из сетки 6x6 и пытаюсь установитьдля желтого это устанавливает его в желтый, но также устанавливает исходный JButton, который также был установлен от красного к желтому.любая помощь будет отличной.спасибо

import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class Grid4 extends JFrame implements ActionListener
    {
        private ColourGrid paintBox = null;
        private JButton fillRed = new JButton("Red");
        private JButton fillYellow = new JButton("Yellow");
        private JButton fillBlue = new JButton("Blue");
        private JButton fillGreen = new JButton("Green");
        private JButton fillPurple = new JButton("Purple");
        private JButton fillBrown = new JButton("Brown");
        private JButton[] paintButton = {fillRed,fillYellow,fillBlue,fillGreen,fillPurple,fillBrown};
        private Color[] colours = {Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, new Color(102, 0, 102), new Color(102, 51, 0)};
        public static void main(String[] args) // sets up a 6x6 grid
        {
            int rows = 6;
            int cols = 6;
            int size = 600;
            Grid4 grid = new Grid4(rows, cols);
            grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            grid.setPreferredSize(new Dimension(size, size));
            grid.pack();
            grid.setLocationRelativeTo(null);
            grid.setVisible(true);
        }
        // main
        public Grid4(int rows, int cols) // makes the 6x6 main grid a grid of JButtons
        {
            int rowSize = 6;
            int colSize = 6;
            int gridSize = 600;
            JButton[][] buttons; //makes an array called buttons
            buttons = new JButton[rowSize][colSize];
            Container pane = getContentPane();
            pane.setLayout(new GridLayout(rows, cols));
            for(int j =0; j < rows; j++){
                for (int i = 0; i < cols; i++) {
                    buttons[j][i] = new JButton("");
                    buttons[j][i].setOpaque(true);
                    buttons[j][i].setName("");
                    buttons[j][i].addActionListener(this);
                    buttons[j][i].setBackground(Color.BLACK);
                    pane.add(buttons[j][i]);
                }
            }
        }               //end of grid constructor

        public void actionPerformed(ActionEvent e) 
        {
            if ( paintBox != null && paintBox.isShowing())//stops more than one paintBox from opening
                paintBox.dispose();
            if( e.getSource() instanceof JButton){// sets
                ((JButton)e.getSource()).setBackground(Color.BLACK);
            } 

            int rows = 6;
            int cols = 1;
            int size = 300;
            paintBox = new ColourGrid(rows, cols,(JButton)e.getSource());
            paintBox.setPreferredSize(new Dimension(size/3, size));
            paintBox.pack();
            paintBox.setVisible(true);
        }

        public class ColourGrid extends JFrame
        { 
            private JButton buttonPress;

            public ColourGrid(int rows, int cols, JButton button)
            {

                buttonPress = button;
                Container pane = getContentPane();
                pane.setLayout(new GridLayout(rows, cols));
                for (int i = 0; i < paintButton.length; i++) {
                    paintButton[i].setOpaque(true);
                    paintButton[i].addActionListener(buttonAction);
                    paintButton[i].setForeground(new Color(100,100,100));
                    paintButton[i].setBackground(colours[i]);
                    pane.add(paintButton[i]);
                }
            }
            private ActionListener buttonAction = new ActionListener()
            {
            public void actionPerformed(ActionEvent a)
            {
                if(a.getSource() instanceof JButton){
                    if((JButton)a.getSource()== fillRed){
                    buttonPress.setBackground(Color.RED);
                    dispose();
                    }
                    else if((JButton)a.getSource()== fillYellow){
                    buttonPress.setBackground(Color.YELLOW);
                    dispose();
                    }
                    else if((JButton)a.getSource()== fillBlue){
                    buttonPress.setBackground(Color.BLUE);
                    dispose();
                    }
                    else if((JButton)a.getSource()== fillGreen){
                    buttonPress.setBackground(Color.GREEN);
                    dispose();
                    }
                    else if((JButton)a.getSource()== fillPurple){
                    buttonPress.setBackground(new Color(102, 0, 102));
                    dispose();
                    }
                    else if((JButton)a.getSource()== fillBrown){
                    buttonPress.setBackground(new Color(102, 51, 0));
                    dispose();
                    }
                } 

            }
        };
        }
    }

1 Ответ

5 голосов
/ 28 марта 2012

Ваша проблема в том, что ваши цветные кнопки находятся в классе Grid4.Каждый раз, когда вы создаете новый объект ColourGrid, вы добавляете те же цветные кнопки в новый ColourGrid JFrame и повторно добавляете ActionListener к тем же кнопкам.Таким образом, каждый раз, когда это происходит, JButtons накапливает другой ActionListener, и довольно скоро, когда нажимается цветная кнопка, запускаются многие ActionListener, старые и новые, и все кнопки меняют цвет.

Решение состоит в том, чтобыЦветные кнопки являются частью класса ColourGrid, а не класса Grid4:

public class ColourGrid extends JFrame {
  private JButton fillRed = new JButton("Red");
  private JButton fillYellow = new JButton("Yellow");
  private JButton fillBlue = new JButton("Blue");
  private JButton fillGreen = new JButton("Green");
  private JButton fillPurple = new JButton("Purple");
  private JButton fillBrown = new JButton("Brown");
  private JButton[] paintButton = { fillRed, fillYellow, fillBlue, fillGreen,
        fillPurple, fillBrown };
  private Color[] colours = { Color.RED, Color.YELLOW, Color.BLUE,
        Color.GREEN, new Color(102, 0, 102), new Color(102, 51, 0) };

  private JButton buttonPress;

Таким образом, каждый раз, когда вы создаете новый объект ColourGrid, он получает свежие новые JButtons с прикрепленным к каждому только одному ActionListener, и толькоизменения цвета самой последней кнопки сетки.

В остальном, все рекомендации, которые Эндрю дал вам, очень хорошие рекомендации.

...