import java.awt.*; import java.awt.event.*; import javax.swing.*; public class s2 extends JFrame{ private JPanel p1, p2; private JButton btnBig,btn; private JComboBox cmcolor; JLabel LBcolor; s2(){ super("改变按钮的颜色"); p1 = new JPanel (new GridLayout (2,1)); p2 = new JPanel(); btnBig = new JButton("请为我选择一种背景颜色"); LBcolor = new JLabel("请选择背景颜色"); cmcolor = new JComboBox(new String[] {"粉色","橙色","绿色"}); p2.add (cmcolor); p2.add (LBcolor); p1.add(p2); cmcolor.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { int color=(int) cmcolor.getSelectedItem(); btn.setBackground(Color.pink); } }); this.add(p1) ; this.setLocation(200, 100); this.setSize(400, 200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[]args) { new s2(); } }
时间: 2024-03-10 22:50:39 浏览: 112
这段代码有几个错误:
1.在代码的第28行,将获取到的下拉框的值强制转换为int类型,但实际上下拉框的值类型为字符串类型,因此会出现类型不匹配的错误。
2.在代码的第29行,将按钮的背景颜色设置为Color.pink,而不是根据选中的下拉框值动态设置按钮背景颜色。
以下是修复后的代码:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class s2 extends JFrame{
private JPanel p1, p2;
private JButton btnBig,btn;
private JComboBox<String> cmcolor;
JLabel LBcolor;
s2(){
super("改变按钮的颜色");
p1 = new JPanel (new GridLayout (2,1));
p2 = new JPanel();
btnBig = new JButton("请为我选择一种背景颜色");
LBcolor = new JLabel("请选择背景颜色");
cmcolor = new JComboBox<>(new String[] {"粉色","橙色","绿色"});
p2.add (cmcolor);
p2.add (LBcolor);
p1.add(p2);
cmcolor.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
String color = (String) cmcolor.getSelectedItem();
switch (color) {
case "粉色":
btn.setBackground(Color.pink);
break;
case "橙色":
btn.setBackground(Color.orange);
break;
case "绿色":
btn.setBackground(Color.green);
break;
}
}
});
btn = new JButton("按钮");
p1.add(btn);
this.add(p1);
this.setLocation(200, 100);
this.setSize(400, 200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[]args) {
new s2();
}
}
```
修复后,可以在下拉框中选择颜色,点击按钮可以看到背景颜色随之改变。
阅读全文