import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI {
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(()->{
var frame=new myFrame();
frame.setTitle("求和与平均");
frame.setVisible(true);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
});
}
}
class myFrame extends JFrame{
Toolkit toolkit=Toolkit.getDefaultToolkit();
Dimension size=toolkit.getScreenSize();
int width=size.width;
int height=size.height;
JPanel inputPanel=new JPanel();
JPanel outputPanel=new JPanel();
JPanel buttonPanel=new JPanel();
JTextArea inputArea=new JTextArea(30,45);
JTextField sumField=new JTextField();
JTextField aveField=new JTextField();
class calculateAction implements ActionListener{
private int n=0;
private double[] data=new double[100];
String s1;
String a;
calculateAction(String s){
char[] d=s.toCharArray();
int i=0;
double sum=0;
int p=0;
boolean ispositive=true;
boolean isinteger=true;
for(char da:d) {
if(da=='-') {
ispositive=false;
}else if(da=='.') {
isinteger=false;
p++;
}else if(da==',') {
if(ispositive) {
data[i]=sum;
}else {
data[i]=sum*(-1);
}
sum=0;
p=0;
ispositive=true;
isinteger=true;
i++;
}else if(Character.isDigit(da)) {
int data=da-'0';
if(isinteger) {
sum=sum*10+data;
}else {
sum=sum+data*Math.pow(0.1, p);
}
p++;
}
}
n=i;
double sum1=0;
double ave;
for(int i1=0;i1<n;i1++) {
System.out.println(data[i1]);
sum1=sum1+data[i1];
}
ave=sum1/n;
s1=String.format("%.3f", sum1);
a=String.format("%.3f",ave);
}
public void actionPerformed(ActionEvent event) {
sumField.setText(s1);
aveField.setText(a);
}
}
myFrame(){
setBounds(width/4,height/4,width/3,height/2);
inputPanel.add(inputArea);
add(inputPanel,BorderLayout.CENTER);
var button=new JButton("计算");
outputPanel.setLayout(new GridLayout(3,2));
outputPanel.add(new JLabel("和值",SwingConstants.CENTER));
outputPanel.add(sumField);
outputPanel.add(new JLabel("平均值",SwingConstants.CENTER));
outputPanel.add(aveField);
buttonPanel.add(button);
outputPanel.add(buttonPanel);
add(outputPanel,BorderLayout.SOUTH);
button.addActionListener(new calculateAction(inputArea.getText()));
}
}
错误界面如上
初学Java,还望各位指点