首页 > 解决方案 > JButton 更改其他按钮颜色,不包括单击的按钮

问题描述

我正在尝试更改每个按钮的颜色,除了单击的按钮。如果我将其更改为仅单击更改其颜色的按钮,则此代码有效。但是,当我将 更改为所需的结果时,出现java.lang.NullPointerException错误。Java 新手不确定如何解决这些错误。谢谢。

public class Hw2 {

    static JButton buttons[] = new JButton[8];
    static Random rand = new Random();
    public static void main(String[] args) {
        //deleted non useful code
        
        for(JButton button: buttons) {
            button = new JButton("Click Me");
            button.setBounds(0,0,50,50); //initialize and set bounds
            
            button.setOpaque(true); //show color and randomly pick
            button.setBackground(new Color(rand.nextInt(256),
                                           rand.nextInt(256), 
                                           rand.nextInt(256)));
            button.setBorderPainted(false);
            
            AnotherHandler bh =new AnotherHandler(button); // add event listener
            button.addActionListener(bh);
            
            panel.add(button);
        }
        
    }
    
    static class AnotherHandler implements ActionListener{
        JButton button;
        AnotherHandler(JButton buttonP){
            button=buttonP;
        }
        @Override
        public void actionPerformed(ActionEvent e) {
            for (JButton but : buttons) {
                but.setBackground(new Color(rand.nextInt(256),
                                            rand.nextInt(256), 
                                            rand.nextInt(256)));
            }
        }
    }
}

标签: javaswingnullpointerexceptionawtjbutton

解决方案


推荐阅读