您的位置:首页 > 其它

17.3

2016-07-27 21:22 211 查看
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class Test_17_3 extends JFrame{
private final int YSTART = 20;
private final int VGAP = 2;
private final int XGAP = 2;
private Color myColor = Color.BLACK;

ButtonGroup group = new ButtonGroup();
JRadioButton jrb1 = new JRadioButton("red");
JRadioButton jrb2 = new JRadioButton("blue");
JRadioButton jrb3 = new JRadioButton("yellow");

trafficPanel tP = new trafficPanel();
public Test_17_3(){

JPanel jgButtons = new JPanel();
jgButtons.setLayout(new GridLayout(1,3));
jgButtons.add(jrb1);
jgButtons.add(jrb2);
jgButtons.add(jrb3);

group.add(jrb1);
group.add(jrb2);
group.add(jrb3);

setLayout(new BorderLayout());
add(jgButtons,BorderLayout.SOUTH);
add(tP,BorderLayout.CENTER);

jrb1.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
myColor = Color.RED;
tP.setColor = true;
repaint();
}

});
jrb2.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
myColor = Color.BLUE;
tP.setColor = true;
repaint();
}

});
jrb3.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
myColor = Color.YELLOW;
tP.setColor = true;
repaint();
}

});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test_17_3 frame = new Test_17_3();
frame.setTitle("Test_17_3");
frame.setSize(300,200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

class trafficPanel extends JPanel{
public boolean setColor = false;

protected void paintComponent(Graphics g){
int xCenter = getWidth()/2;
int yCenter = getHeight()/2;

int radius = getHeight() /6 - 5;
/** draw steady shape */
//draw rect
g.drawRect(xCenter -radius,YSTART, 2*radius,getHeight()-20 -VGAP);
//draw three circles
g.drawOval(xCenter - radius + XGAP, YSTART + VGAP, 2*radius -2*XGAP , 2*radius-2*XGAP);
g.drawOval(xCenter - radius + XGAP, YSTART + 2*radius + 2*VGAP,2*radius -2*XGAP , 2*radius-2*XGAP);
g.drawOval(xCenter - radius + XGAP, YSTART + 4*radius + 3*VGAP,2*radius -2*XGAP , 2*radius-2*XGAP );

if(setColor)
{
if(myColor == Color.RED)
{g.setColor(Color.RED); g.fillOval(xCenter - radius + XGAP, YSTART + VGAP, 2*radius -2*XGAP , 2*radius-2*XGAP);}
else if(myColor == Color.BLUE)
{g.setColor(Color.BLUE); g.fillOval(xCenter - radius + XGAP, YSTART + 2*radius + 2*VGAP,2*radius -2*XGAP , 2*radius-2*XGAP);}
else
{g.setColor(Color.YELLOW);g.fillOval(xCenter - radius + XGAP, YSTART + 4*radius + 3*VGAP,2*radius -2*XGAP , 2*radius-2*XGAP );}
}
}
}
}


Test_17_3.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: