3个回答
展开全部
按照你的要求,写出的程序如下:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TrafficLight {
JFrame jf=new JFrame("Traffic Light");
JPanel jp=new JPanel();
JComboBox jcb=new JComboBox();
public TrafficLight(){
jcb.addItem("红灯");
jcb.addItem("黄灯");
jcb.addItem("绿灯");
jcb.addItemListener(new JComboBoxListener());
jf.add(jcb,BorderLayout.NORTH);
jf.add(jp,BorderLayout.CENTER);
jf.setSize(400,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new TrafficLight();
}
class JComboBoxListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent ie) {
Graphics g=jf.getGraphics();
if(ie.getItem().equals("红灯")){
g.setColor(Color.RED);
g.fillOval(200, 200, 100, 100);
}else if(ie.getItem().equals("黄灯")){
g.setColor(Color.YELLOW);
g.fillOval(200, 200, 100, 100);
}else if (ie.getItem().equals("绿灯")){
g.setColor(Color.GREEN);
g.fillOval(200, 200, 100, 100);
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TrafficLight {
JFrame jf=new JFrame("Traffic Light");
JPanel jp=new JPanel();
JComboBox jcb=new JComboBox();
public TrafficLight(){
jcb.addItem("红灯");
jcb.addItem("黄灯");
jcb.addItem("绿灯");
jcb.addItemListener(new JComboBoxListener());
jf.add(jcb,BorderLayout.NORTH);
jf.add(jp,BorderLayout.CENTER);
jf.setSize(400,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new TrafficLight();
}
class JComboBoxListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent ie) {
Graphics g=jf.getGraphics();
if(ie.getItem().equals("红灯")){
g.setColor(Color.RED);
g.fillOval(200, 200, 100, 100);
}else if(ie.getItem().equals("黄灯")){
g.setColor(Color.YELLOW);
g.fillOval(200, 200, 100, 100);
}else if (ie.getItem().equals("绿灯")){
g.setColor(Color.GREEN);
g.fillOval(200, 200, 100, 100);
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询