2016年2月16日 星期二

JAVA GUI GridChangeColor.java

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

public class GridChangeColor implements ItemListener
{
JFrame f = new JFrame("變色龍");
JPanel p = new JPanel();
String[] cname = {"紅","橙","黃","綠"};
JRadioButton[] cb = new JRadioButton[4];

public static void main(String[] args)
{
GridChangeColor test = new GridChangeColor();
test.init();
}

public void init()
{
Container contentPane = f.getContentPane();
contentPane.add(p,"Center");
JPanel up = new JPanel();
contentPane.add(up,"North");
up.setLayout(new GridLayout(2,2));
ButtonGroup g = new ButtonGroup();
//用迴圈加入每個單選紐,設定其傾聽者
for(int i=0;i {
cb[i] = new JRadioButton(cname[i]);
up.add(cb[i]);
g.add(cb[i]);
cb[i].addItemListener(this);
}
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(320,240);
f.setVisible(true);
}
        //單選紐被選擇取及取消的事件處理方法
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
//取得產生事件的按鈕
JRadioButton s = (JRadioButton) e.getSource();
//將 p 的背景顏色換成對應的顏色
if(s == cb[0]) p.setBackground(Color.red);
else if(s == cb[1]) p.setBackground(Color.orange);
else if(s == cb[2]) p.setBackground(Color.yellow);
else p.setBackground(Color.green);
}
}

}

沒有留言: