1 Bài 2 - Buổi 3 Mon Nov 05, 2012 9:48 am
Admin
Admin
- Code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.event.MouseInputAdapter;
public class Bai2 extends MouseInputAdapter {
JFrame frame;
JRadioButton r,y,g;
JPanel select;
Table led;
Bai2(){
frame = new JFrame();
frame.setTitle("Đèn giao thông");
frame.setSize(260, 200);
frame.setLocation(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
r = new JRadioButton("Đèn đỏ");
y = new JRadioButton("Đèn vàng");
g = new JRadioButton("Đèn xanh");
led = new Table();
ButtonGroup group = new ButtonGroup();
group.add(r);
group.add(y);
group.add(g);
r.addMouseListener(this);
y.addMouseListener(this);
g.addMouseListener(this);
select = new JPanel(new FlowLayout());
select.add(r);
select.add(y);
select.add(g);
frame.add(led,BorderLayout.CENTER);
frame.add(select,BorderLayout.SOUTH);
frame.add(led);
frame.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent e){
if (r.isSelected()){
led.setColor("do");
led.repaint();
}
else
if (y.isSelected()){
led.setColor("vang");
led.repaint();
}
else
if (g.isSelected()){
led.setColor("xanh");
led.repaint();
}
}
public static void main(String[] args) {
Bai2 obj = new Bai2();
}
}
class Table extends JPanel{
String color = "nuil";
public void setColor(String color){
this.color = color;
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(30, 30, 190, 70);
g.setColor(Color.red);
g.drawRoundRect(40, 40, 50, 50, 50, 50);
g.setColor(Color.yellow);
g.drawRoundRect(100, 40, 50, 50,50,50);
g.setColor(Color.green);
g.drawRoundRect(160, 40, 50, 50,50,50);
if (color.equals("do")){
g.setColor(Color.red);
g.fillRoundRect(40, 40, 50, 50, 50, 50);
}
else
if (color.equals("vang")){
g.setColor(Color.yellow);
g.fillRoundRect(100, 40, 50, 50,50,50);
}
else
if (color.equals("xanh")){
g.setColor(Color.green);
g.fillRoundRect(160, 40, 50, 50,50,50);
}
}
}