Java--GUI編程(二)簡易加法計算器



import
javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Calculate extends Frame{ TextField num1,num2,num3; public Calculate() { //三個文字域 num1 = new TextField(10); num2 = new TextField(10); num3 = new TextField(20); //一個按鈕 Button button = new Button("="); button.addActionListener(new CalculateListener()); //一個標簽 Label label = new Label("+"); setLayout(new FlowLayout()); add(num1); add(label); add(num2); add(button); add(num3); pack(); setVisible(true); } class CalculateListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { int i1 = Integer.parseInt( num1.getText()); int i2 = Integer.parseInt( num2.getText()); num1.setText(""); num2.setText(""); num3.setText(String.valueOf(i1+i2)); } } public static void main(String[] args) { new Calculate(); } }

 

 

一個簡易的加法計算器

利用到了事件監聽器

監聽按鈕的變換從而使按鈕有所作為。

在這個方法中完整的實現了真正的Java的面向對象。

而不是面向過程

利用方法與屬性 構建了這個加法計算器

其中利用了內部類:最大的好處就是們可以暢通無阻的訪問外部的屬性和方法!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM