【发布时间】:2018-10-22 18:23:32
【问题描述】:
有人能告诉我为什么我的 ActionListener 不工作吗? 我用 JFrame 创建了一个寡妇,用 JButton 创建了一些按钮。
需要JPanel吗?
我想更改窗口的背景颜色。这是行不通的。如果我尝试buttonz[0].setBackground(Color.red);,只有按钮的颜色会改变。但我想改变窗口的背景。
public class ColorButtons implements Runnable {
public static void main(String args[]) {
new ColorButtons().init();
}
public void init() {
//Creating window
JFrame frame = new JFrame();
frame.setVisible (true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1000,400);
frame.setLayout(new FlowLayout(FlowLayout.CENTER,100,100));
//creating buttons
JButton[] buttonz = {
new JButton("Red"),
new JButton("Yellow"),
new JButton("Blue"),
new JButton("Green")};
//adding my buttons
for (int i = 0; i < buttonz.length; i++) {
frame.add(buttonz[i]);
final int j = i;
buttonz[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch (j) {
case 0:
frame.setBackground(Color.red);
break;
case 1:
frame.setBackground(Color.yellow);
break;
case 2:
frame.setBackground(Color.blue);
break;
default:
frame.setBackground(Color.green);
break;
}
}
});
}
}
@Override
public void run() {
}
}
【问题讨论】:
-
请更好地定义“不起作用”。细节很重要。
-
我想更改窗口的背景颜色。这是行不通的。如果我尝试 buttonz[0].setBackground(Color.red);只有按钮的颜色会改变。但我想改变窗口的背景。
-
edit您对此信息的问题
标签: java swing jframe jbutton actionlistener