Java实训——编写一个窗体应用程序模拟交通信号灯。

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cxy201658503125/article/details/78505657

实训要求:


代码:

import java.awt.*;  
import java.awt.event.*;  
import javax.swing.*;  
  
import java.awt.Graphics;  
  
public class MainClass extends JFrame {  
    public JComboBox box;  
    int flag = 0;  
    jpNewPanel jpNewPanel;  
  
    public static void main(String[] args) {  
    	MainClass frame = new MainClass();  
    	frame.setBounds(650,300,550,550);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("信号灯"); 
        frame.setVisible(true);  
    }  
  
    public MainClass() {  
        box = new JComboBox();  
        box.addItem("请选择");  
        box.addItem("红灯");  
        box.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                flag = box.getSelectedIndex(); 
                jpNewPanel.repaint();  
            }  
        });  
        box.addItem("黄灯");  
        box.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                flag = box.getSelectedIndex();
                jpNewPanel.repaint();  
            }  
        });  
        box.addItem("绿灯");  
        box.addActionListener(new ActionListener() {  
            public void actionPerformed(ActionEvent e) {  
                flag = box.getSelectedIndex();  
                jpNewPanel.repaint();  
            }  
        });  
        add(box, BorderLayout.NORTH);  
        jpNewPanel = new jpNewPanel();  
        add(jpNewPanel, BorderLayout.CENTER);  
    }  
    class jpNewPanel extends JPanel {  
        protected void paintComponent(Graphics g) {  
            super.paintComponent(g);  
            g.drawOval(150, 0, 120, 120);  
            if (flag == 1) {  
                g.setColor(Color.RED);  
                g.fillOval(150, 0, 120, 120);  
            } else if (flag == 2) {  
                g.setColor(Color.YELLOW);  
                g.fillOval(150, 0, 120, 120);  
            } else if (flag == 3) {  
                g.setColor(Color.GREEN);  
                g.fillOval(150, 0, 120, 120);  
            }  
        }  
    }  
} 

运行结果:


小结:学习了如何添加画布。


展开阅读全文

没有更多推荐了,返回首页