* Copyright (c) 2012, 煙臺大學計算機學院學生
* All rights reserved.
* 作 者: 劉鎮
* 完成日期: 2012 年 11 月 04 日
* 版 本 號: 2.011
* 對任務及求解方法的描述部分
* 問題描述:編寫一個JFrame,標題爲“計算的窗口”,在該窗口中組件的佈局是FlowLayout。窗口中添加兩個文本區,當我們在一個文本區中輸入若干個數時,另一個文本區同時對輸入的數進行求和運算並求出平均值,也就是說隨着輸入的變化,另一個文本區不斷地更新求和及平均值。
*代碼部分:
MyJFrame.java:
package lz_10w;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
//import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JFrame;
public class MyJFrame extends JFrame implements TextListener, ActionListener
{
TextArea text1;
TextArea text2;
Button button;
//MyImageJPanel image;
public MyJFrame()
{
setExtendedState(Frame.MAXIMIZED_VERT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(450, 150, 100, 200);
setSize(500, 500);
this.setTitle("計算的窗口");
//setLocationRelativeTo(this);
Container con = getContentPane();
con.setLayout(new FlowLayout());
//image = new MyImageJPanel();
//image.setBounds(0, 0, this.getWidth(), this.getHeight());
text1 = new TextArea();
text2 = new TextArea();
button = new Button("清空");
button.setBackground(Color.lightGray);
//con.add(image);
con.add(text1);
con.add(text2);
con.add(button);
text2.setEditable(false);
text1.addTextListener(this);
button.addActionListener(this);
setVisible(true);
validate();
}
public void textValueChanged(TextEvent e) {
String s = text1.getText();
StringTokenizer st = new StringTokenizer(s, " ,'\n'");
int n = st.countTokens();
String a[] = new String[n];
for(int i = 0; i <= n - 1; i++)
{
String temp = st.nextToken();
a[i] = temp;
}
double addResult = 0;
double aveResult = 0;
for(int i = 0; i < n; i++)
{
addResult += Double.valueOf(a[i]);
}
if(n != 0)
{
aveResult = addResult / n;
}
text2.setText(null);
text2.append(n + "個數相加的和: " + addResult + "\n");
DecimalFormat d = new DecimalFormat("#.00");
text2.append("平均值: " + d.format(aveResult) + "\n");
}
public void actionPerformed(ActionEvent e) {
text1.setText(null);
}
}
TestJFrame.java:
package lz_10w;
public class TestJFrame {
/**
* @param args
*/
public static void main(String[] args) {
MyJFrame jf = new MyJFrame();
}
}
運行測試:
心得經驗:
還可以,能實現任意輸入數字,求平均值和求和,但美中不足,還沒添加圖片背景,試過幾次,都不成功,需要再研究研究,其次就是沒對異常進行處理。