java - 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)));
}
}
}
}
解决方案
推荐阅读
- codeigniter - 有没有办法将文本框和复选框的数组从视图发送到控制器(CodeIgniter)
- jquery - 如果 {{ value[#] }} 为空,则隐藏模态按钮
- game-development - 在 Godot 引擎中添加精灵时无法获取选项
- php - 实时服务器上的 IIS / PHPMailer 身份验证问题,但在本地主机上工作
- javascript - 如何使用 Bootstrap 以表格格式显示嵌套 json 的所有字段
- javascript - 如何在 React Redux 应用程序中映射图像数组?
- javascript - 为什么我的 JS 代码中的 clearForm() 不起作用?
- netlogo - Netlogo:请特定的乌龟做某事
- python - Regionprops 总是找到一个区域 - python
- winforms - 使用 tel 协议从 vb.net 发起出站电话