trafficframe.java

来自「编写一个Swing应用程序」· Java 代码 · 共 70 行

JAVA
70
字号

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class trafficFrame extends SimpleFrame{
    public trafficFrame(int width,int height) {
        super(width,height);
        setTitle("红绿灯");
        ColorPanel panel=new ColorPanel();
        Container contentPane=getContentPane();
        contentPane.add(panel);
    }
    
    public static void main(String[] args){
        trafficFrame frame=new trafficFrame(400,300);
        frame.setVisible(true);
    }    
}

class ColorPanel extends JPanel{
    public ColorPanel(){
        redButton= new  JButton("红灯");
        greenButton=new  JButton("绿灯");
        yellowButton=new  JButton("黄灯");
        add(redButton);
        add(greenButton);
        add(yellowButton);
        redButton.addActionListener(new ColorActionListener());
        yellowButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                setyellow();
            }
        });
        greenButton.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent event){
                setgreen();
            }
        });
    }
    
    private void setyellow(){
        backgroundColor=backgroundColor.brighter();
		backgroundColor=new Color(255,255,0);
        setBackground(backgroundColor);
    }
    
    private void setgreen(){
        backgroundColor=backgroundColor.darker();
        backgroundColor=new Color(0,255,0);
        setBackground(backgroundColor);
    }
    
    private class ColorActionListener implements ActionListener{
        public void actionPerformed(ActionEvent event){
                setColor();
            }
    }
    
	private void setColor(){
        backgroundColor=new Color(255,0,0);
        setBackground(backgroundColor);
    }
    
    private Color backgroundColor;
    private JButton redButton;
    private JButton greenButton;
    private JButton yellowButton;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?