java實現(xiàn)計算器加法小程序(圖形化界面)
對于一個簡單的計算器加法小程序,它首先是由五個組件構(gòu)成的,三個文本框,兩個用來輸入數(shù)字,一個用來輸出最后的結(jié)果,接下來是一個標(biāo)簽,標(biāo)簽的內(nèi)容是加號,表示這里計算的是加法,最后一個組建是一個按鈕,點擊該按鈕時會輸出計算的結(jié)果.在這個小程序中,我們采用的布局管理器時FlowLayout.基本元素就是這些,接下來我們將演示兩種實現(xiàn)的方法:
(1)、傳遞成員局部變量的方法,具體代碼如下:
package 實例11; import java.awt.*; import java.awt.event.*; public class Test { public static void main(String[]args){ new MyFrame().launchMyFrame(); } } class MyFrame extends Frame{ public void launchMyFrame(){ TextField tf1 = new TextField(); TextField tf2 = new TextField(); TextField tf3 = new TextField(); Label l = new Label("+"); Button b = new Button("="); Monitor m = new Monitor(tf1, tf2, tf3); //通過構(gòu)造方法將三個局部變量傳遞Monitor b.addActionListener(m); setLayout(new FlowLayout()); add(tf1); add(l); add(tf2); add(b); add(tf3); pack(); setVisible(true); } } class Monitor implements ActionListener{ TextField tf1, tf2, tf3; public Monitor(TextField tf1, TextField tf2, TextField tf3){ this.tf1 = tf1; this.tf2 = tf2; this.tf3 = tf3; } public void actionPerformed(ActionEvent e){ int a = Integer.parseInt(tf1.getText()); int b = Integer.parseInt(tf2.getText()); int c = a + b; tf3.setText(""+c); System.out.println(c); } }
(2)、傳遞引用的方式,具體代碼如下:
package 實例11; import java.awt.*; import java.awt.event.*; public class Test { public static void main(String[]args){ new MyFrame().launchMyFrame(); } } class MyFrame extends Frame{ TextField tf1, tf2, tf3; public void launchMyFrame(){ tf1 = new TextField(); tf2 = new TextField(); Label l = new Label("+"); Button b = new Button("="); Monitor m = new Monitor(this); b.addActionListener(m); setLayout(new FlowLayout()); add(tf1); add(l); add(tf2); add(b); add(tf3); pack(); setVisible(true); } } class Monitor implements ActionListener{ MyFrame mf = null; public Monitor(MyFrame mf){ this.mf = mf; } public void actionPerformed(ActionEvent e){ int a = Integer.parseInt(mf.tf1.getText()); int b = Integer.parseInt(mf.tf2.getText()); int c = a + b; mf.tf3.setText(""+c); System.out.println(c); } }
總結(jié):通常使用第二種方法比較好,因為只需要在事件監(jiān)聽器中接收引起事件發(fā)生的類的引用即可,無需知道該類中具體的成員
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合ShardingSphere的示例代碼
本文主要介紹了SpringBoot整合ShardingSphere的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09IDEA2021.2永久激活碼最新超詳細(xì)(激活到2099)
這篇文章主要介紹了IDEA2021.2永久激活碼,是idea2021版最新激活方法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09spring Cloud微服務(wù)跨域?qū)崿F(xiàn)步驟
這篇文章主要介紹了spring Cloud微服務(wù)跨域?qū)崿F(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11spring?boot?3使用?elasticsearch?提供搜索建議的實例詳解
這篇文章主要介紹了spring?boot3使用elasticsearch提供搜索建議,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08