/***************************************** 算圓形面積,處理兩個以上的按鈕 *************************************************/ import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ui6 extends JFrame { Container c; JLabel lab1,ans; JTextField txt1; JButton bot0,bot1,bot2; public ui6() //建構元 { super("計算圓形面積"); c=getContentPane(); setSize(640,480); lab1=new JLabel("請輸入半徑:"); txt1=new JTextField(10); bot1=new JButton("算周長"); bot2=new JButton("算面積"); bot0=new JButton("結束程式"); ans=new JLabel("沒有任何答案!"); c.setLayout(new FlowLayout(FlowLayout.CENTER));//設定為流水版面設定 //注意加入元件的順序 c.add(lab1); c.add(txt1); c.add(bot1); c.add(bot2); c.add(ans); c.add(bot0); bot0.addActionListener(new imgZ0());//設定自己為bot0按鈕的傾聽者 bot1.addActionListener(new imgZ1());//設定自己為bot1按鈕的傾聽者 bot2.addActionListener(new imgZ2());//設定自己為bot2按鈕的傾聽者 setVisible(true); } public void paint(Graphics g) //真正的畫圖設定 { super.paint(g);//畫出元件 } /***按鈕事件的傾聽類別****/ class imgZ0 implements ActionListener { public void actionPerformed(ActionEvent e) //按鈕事件的處理方法 { //結束程式 System.exit(0); } } class imgZ1 implements ActionListener { public void actionPerformed(ActionEvent e) //按鈕事件的處理方法 { double cans=0,radius; //算周長 radius=Double.parseDouble(txt1.getText());//取得半徑 cans=radius*2*Math.PI; //用系統提供的PI,別用自己亂設的3.1416 ans.setText("周長="+cans); repaint();//要程式重新執行一次paint() } } class imgZ2 implements ActionListener { public void actionPerformed(ActionEvent e) //按鈕事件的處理方法 { double cans=0,radius; //算面積 radius=Double.parseDouble(txt1.getText());//取得半徑 cans=radius*radius*Math.PI; //用系統提供的PI,別用自己亂設的3.1416 ans.setText("面積="+cans); repaint();//要程式重新執行一次paint() } } /***主程式***/ public static void main(String args[]) //程式起點 { ui6 app=new ui6(); //畫圖 app.addWindowListener(new WindowAdapter(){ //匿名內部類別 public void windowClosing(WindowEvent e) { System.exit(0); } }); //處理視窗關閉要求 } }