MyJFrame.java
import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.text.DecimalFormat;
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
public class TestJFrame {
public static void main(String[] args) {
MyJFrame jFrame=new MyJFrame();
}
}