📄 traffic.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class traffic extends SimpleFrame{
public traffic(int width,int height) {
super(width,height);
setTitle("红绿灯");
ColorPanel panel=new ColorPanel();
Container contentPane=getContentPane();
contentPane.add(panel);
}
public static void main(String[] args){
traffic frame=new traffic(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(){
w=3;
repaint();
}
private void setgreen(){
w=2;
repaint();
}
private class ColorActionListener implements ActionListener{
public void actionPerformed(ActionEvent event){
setred();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
switch(w){
case 1:g.setColor(Color.RED);
g.fillOval(90,100,50,50);
break;
case 2:g.setColor(Color.GREEN);
g.fillOval(160,100, 50, 50);
break;
case 3:g.setColor(Color.yellow);
g.fillOval(230,100, 50, 50);
}
}
private void setred(){
w=1;
repaint();
}
private Color backgroundColor;
private Color g;
private JButton redButton;
private JButton greenButton;
private JButton yellowButton;
public int w;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -