简体   繁体   English

如何使用 actionListener 更改 JButton 的颜色

[英]How do I change the color of a JButton with actionListener

I have the following JFrame.我有以下 JFrame。 enter image description here在此处输入图片说明

It contains a JButton[100] of square and circle JButtons.它包含一个由方形和圆形 JButton 组成的 JButton[100]。 I want to change their color when I click on them.当我点击它们时,我想改变它们的颜色。 So I use actionListener for that.所以我为此使用了 actionListener。 But when I write the actionListener to change the color it gives me an exception但是当我编写 actionListener 来改变颜色时,它给了我一个例外

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: Index 100 out of bounds for length 100线程“AWT-EventQueue-0”中的异常java.lang.ArrayIndexOutOfBoundsException:索引100超出长度100的范围

and it says that the exception is at the b[i].setBackground(Color.blue);它说异常在 b[i].setBackground(Color.blue); inside the actionListener.在 actionListener 中。 I've searched a lot and nothing is changing the color but just gives the exception.我已经搜索了很多,但没有改变颜色,但只是给出了例外。 Here is my code这是我的代码

Subject.java主题.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圆环.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, 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, 0, getSize().width - 1, 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, 0, getWidth(), getHeight());
        }
        return shape.contains(x, y);
      }
}

I've also tried the following but nothing has changed.我也尝试了以下但没有任何改变。

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

Does anyone have any advice on what to do to fix it?有没有人对如何修复它有任何建议? Thank you!谢谢!

Simply change the following line in your actionPerformed() method...只需在actionPerformed()方法中更改以下行...

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

to this...到这...

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

You are creating a separate, anonymous class (that implements ActionListener interface) for each JButton .您正在为每个JButton创建一个单独的匿名类(实现ActionListener接口)。 Hence the ActionEvent source can only be the JButton that you created the anonymous class for.因此ActionEvent只能是您为其创建匿名类的JButton

Note that after you compile your java code, you will have a separate class file for each ActionListener .请注意,在编译完 Java 代码后,每个ActionListener都会有一个单独的类文件。 The class file names will begin with Subject$ and end with .class , for example:类文件名将以Subject$开头并以.class结尾,例如:

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

There will be at least 100 of these classes since you have created one for each JButton .因为您已经为每个JButton创建了一个类,所以至少会有 100 个这样的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用JButton ActionListener关闭程序? - How do I shutdown my program with a JButton ActionListener? 如何将ActionListener放在使用Jbuttons的ArrayList创建的JButton上 - How do I put an ActionListener on a JButton created with an ArrayList of Jbuttons 如何将ActionListener添加到扩展JButton的类的实例中? - How do I add an ActionListener to an instance of my class that extends JButton? 如何在Java中更改实际JButton的颜色? 不是背景,不是文字 - How do I change the color of an actual JButton in Java? Not the background and not the text 如何使用JButton更改JPanel的背景颜色? - How do I change the background color of a JPanel with a JButton? 如何在JButton ActionListener中访问变量? - How can I access a variable in an JButton ActionListener? 如何将 ActionListener 添加到 JButton - How to add ActionListener to JButton 如何使用 ActionListener 更改 JPanel 的颜色 - How to change color of JPanel with ActionListener 如何在 JButton 上使用 ActionListener 来更改 JPanel 容器内的 JLabel 组件的背景? - How can I use an ActionListener on a JButton to change the background of a JLabel component inside of a JPanel container? Java:如何将变量从JButton ActionListener传递给主类? - Java: How do I pass variables from JButton ActionListener to main class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM