如何使用actionListener更改JButton的颜色

问题描述

我有以下JFrame。 enter image description here

它包含正方形和圆形JButton的JButton [100]。我想在单击它们时更改它们的颜色。因此,我使用actionListener。但是当我编写actionListener来更改颜色时,它给了我一个例外

线程“ AWT-EventQueue-0”中的异常java.lang.Arrayindexoutofboundsexception:索引100的长度为100超出范围

表示异常在b [i] .setBackground(Color.blue);处。在actionListener中。 我进行了很多搜索,没有改变任何颜色,只是给出了例外。 这是我的代码

Subject.java

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

public class Subject extends JFrame{
    public Subject() {
        super("Subject");
        p = new JPanel(new GridLayout(10,10));
        b = new JButton[100];
        Random r = new Random();
        for(i=0;i<100;i++) {
            y = r.nextInt(2) +1;
            if(y==1) {
                b[i] = new JButton();
                b[i].setBackground(Color.black);
                b[i].setPreferredSize(new Dimension(35,35));
                p.add(b[i]);
            }else {
                b[i] = new Circle();
                b[i].setBackground(Color.black);
                p.add(b[i]);
            }
            b[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    b[i].setBackground(Color.blue);
                }
            }); 
        }
        add(p);
        pack();
        setVisible(true);
        setDefaultCloSEOperation(EXIT_ON_CLOSE);
        setLocation(100,200);
    }
    
    private JPanel p;
    private JButton[] b;
    private int i,y;
    
}

Circle.java

import java.awt.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;

public class Circle extends JButton{
    public Circle() {
        setBackground(Color.red);
        setFocusable(false);
     
        /*
         These statements enlarge the button so that it 
         becomes a circle rather than an oval.
        */
        Dimension size = getPreferredSize();
        size.width = size.height = Math.min(35,35);
        setPreferredSize(size);
     
        /*
         This call causes the JButton not to paint the background.
         This allows us to paint a round background.
        */
        setContentAreaFilled(false);
      }
     
      protected void paintComponent(Graphics g) {
        if (getModel().isArmed()) {
          g.setColor(Color.yellow);
        } else {
          g.setColor(getBackground());
        }
        g.filloval(0,getSize().width - 1,getSize().height - 1);
        JLabel l = new JLabel("Click Me");
        
        super.paintComponent(g);
      }
     
      protected void paintBorder(Graphics g) {
        g.setColor(Color.darkGray);
        g.drawoval(0,getSize().height - 1);
      }
     
      // Hit detection.
      Shape shape;
     
      public boolean contains(int x,int y) {
        // If the button has changed size,make a new shape object.
        if (shape == null || !shape.getBounds().equals(getBounds())) {
          shape = new Ellipse2D.Float(0,getWidth(),getHeight());
        }
        return shape.contains(x,y);
      }
}

我也尝试了以下方法,但没有任何改变。

b[i].addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (e.getSource()==b[i])
                    {
                        b[i].setBackground(Color.blue);
                    }
                }
            }); 

有人对如何解决该问题有任何建议吗?谢谢!

解决方法

只需在您的actionPerformed()方法中更改以下行...

b[i].setBackground(Color.blue);

对此...

((JButton) e.getSource()).setBackground(Color.blue);

您正在为每个ActionListener创建一个单独的匿名类(实现JButton接口)。因此,ActionEvent源只能 是您为其创建匿名类的JButton

请注意,编译Java代码后,每个ActionListener都有一个单独的类文件。类文件名将以Subject$开头,以.class结尾,例如:

Subject$1.class
Subject$2.class
Subject$3.class

由于您为每个JButton创建了一个类,因此至少有100个此类。