Java第二次作业第四题

文本行输入学生姓名,下来框选择课程名称,文本行输入课程成绩;点击“录入”按钮,相关信息显示在文本区;点击“统计”按钮,将所有录入的成绩的平均成绩显示在另一个文本行中。

package naizi;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class UserJFrame extends JFrame implements ActionListener
{
private JTextField text_name,text_avescore,text_score;
private JComboBox combobox_course;           
private JButton button_add,button_statistics;                                  
private JTextArea text_user;
private int sum=0,count=0;

public UserJFrame(){
    this.setSize(360,200);
    this.setLocation(300,240);
    this.getContentPane().setLayout(new GridLayout(1,2,5,5));//网格布局 

    text_user = new JTextArea();
    this.getContentPane().add(text_user);
    
    JPanel panel = new JPanel(new GridLayout(6,1,1,1)); //网格布局
    this.getContentPane().add(panel);  
    
    text_name = new JTextField("姓名");
    panel.add(text_name);
    
    Object course[]={"Java", "C++"};
    combobox_course = new JComboBox(course);
    panel.add(combobox_course);
    
    text_score = new JTextField("0");
    panel.add(text_score);
    
    button_add = new JButton("添加");
    button_add.addActionListener(this);   //注册监听事件
    panel.add(button_add);
    
    text_avescore = new JTextField("平均成绩");
    panel.add(text_avescore);
    
    button_statistics = new JButton("统计");
    button_statistics.addActionListener(this);    //注册监听事件;
    panel.add(button_statistics);
    this.setVisible(true);//显示界面

}

public void actionPerformed(ActionEvent e){    //单击事件处理方法
    if (e.getSource()== button_add){   //判断事件源
        String aline="";
        aline = text_name.getText();
        aline += ", "+combobox_course.getSelectedItem(); 
        aline += ", "+text_score.getText();
        text_user.append(aline+"\n");  //追加到文本区
//      text_user.setText(aline);  //追加到文本区 
        sum=sum+Integer.valueOf(text_score.getText());//计算总分
        count++;
        text_score.setText("0");
    }
    if (e.getSource() == button_statistics){
        text_avescore.setText(Integer.toString(sum/count));
    }//设置统计成绩
    
}
public static void  main(String [] args){   
    new UserJFrame();//运行程序窗体
}
}  

运行结果如图:

猜你喜欢

转载自www.cnblogs.com/zqm-sau/p/9807692.html