Swing

210824_Swing+radiobutton+arrays+actionlistener

요옫 2021. 8. 24. 17:34

public class A_SwingRadioEx06 extends JFrame implements ActionListener{

 

Container cp;

JRadioButton g[]= new JRadioButton[2];

JRadioButton c[]= new JRadioButton[3];

JLabel lbl;

 

String gender[]= {"남자","여자"};

String color[]= {"Red","Blue","Pink"};

Color colors[]= {Color.RED,Color.BLUE,Color.PINK};

 

 

public A_SwingRadioEx06(String title) {

super(title);

 

cp=this.getContentPane();

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setBounds(700,100,600,600); 

cp.setBackground(new Color(151,190,200));

 

initDesign();

this.setVisible(true);

}

 

 

public void initDesign() {

 

this.setLayout(null);

 

int xpos=70;  //xpos의 초기값

ButtonGroup bg1=new ButtonGroup();

for(int i=0;i<g.length;i++)

{

g[i]=new JRadioButton(gender[i],i==1?true:false);

g[i].setBounds(xpos, 50, 100, 40);

g[i].setOpaque(false);

g[i].setFont(new Font("",Font.BOLD,20));

g[i].addActionListener(this);

 

bg1.add(g[i]);

this.add(g[i]);

xpos+=80;

}

 

xpos=70;

ButtonGroup bg2=new ButtonGroup();

for(int i=0;i<c.length;i++)

{

c[i]=new JRadioButton(color[i],i==1?true:false);

c[i].setBounds(xpos, 100, 100, 40);

c[i].setOpaque(false);

c[i].setFont(new Font("",Font.BOLD,20));

c[i].addActionListener(this);

 

bg2.add(c[i]);

this.add(c[i]);

xpos+=80;

}

 

lbl=new JLabel("나는 여자입니다",JLabel.CENTER);

lbl.setFont(new Font("",Font.BOLD,20));

lbl.setBorder(new LineBorder(Color.BLACK,5));

lbl.setBounds(70, 220, 350, 70);

this.add(lbl);

}

 

 

public static void main(String[] args) {

new A_SwingRadioEx06("Radio Quiz");

}

 

@Override

public void actionPerformed(ActionEvent e) {

Object ob=e.getSource();

 

if(ob==g[0])

{

lbl.setText("나는 남자입니다");

}

else if(ob==g[1])

{

lbl.setText("나는 여자입니다");

}

 

    for(int i=0;i<c.length;i++)

    {

    if(ob==c[i])

    {

    lbl.setForeground(colors[i]);

    }

    }

}

}