2014年4月16日 星期三

Swing:元件:JRadioButton 與 事件處理

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;

class Frame10 extends JFrame implements ActionListener{
 private JPanel contentPane;
 ButtonGroup buttonGroup;
 JRadioButton[] radioButton;

 Frame10(){
  
  contentPane = new JPanel();
  add(contentPane);
  contentPane.setBounds(10, 20, 100, 120);
  Border line = BorderFactory.createLineBorder(Color.black);
  contentPane.setBorder(BorderFactory.createTitledBorder(line,"性別"));
  contentPane.setLayout(new FlowLayout(FlowLayout.LEFT));
  
  buttonGroup = new ButtonGroup();
  
  radioButton = new JRadioButton[2];
  radioButton[0] = new JRadioButton("男",false);
  radioButton[1] = new JRadioButton("女",false);
  
  for(int i=0; i < radioButton.length; i++){
   contentPane.add(radioButton[i]);
   radioButton[i].addActionListener(this);
  }
  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setLayout(null);
  setBounds(0,0,450,300);
  setTitle("Swing JFrame 視窗");
  setVisible(true);
 }
 
 public void actionPerformed(ActionEvent e){
  String str;
  if(radioButton[0].isSelected())
   str = "男性";
  else
   str = "女性";
  JOptionPane.showMessageDialog(null, "性別: " + str);
  
  for(int i=0; i < radioButton.length; i++)
   radioButton[i].setSelected(false);
 }
}
public class FrameRadio {

 public static void main(String[] args) {
  Frame10 frame = new Frame10();
 }

}


執行結果





















按下按鈕鍵時

沒有留言:

張貼留言