这个程序里面用到了为面板(JPanel)设置的布局管理器,以及如何获取系统的当前日期等技术,而且有一定的趣味性。读者可以自己再加一些判断,比如当计算出的人品值很低时给出趣味性的提示:“是我不好,不应该诱惑你来测试你的人品。。。”,这样的话可能会更有意思。更全面的人品测试器将在后续的文章里与大家见面。
package text;
import javax.swing.*;
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextGraphics extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
protected JPanel panel=new JPanel();
protected JLabel label=new JLabel("今日人品测试(满分为100分)");
protected JTextArea displayArea=new JTextArea(15,30);
protected JLabel info=new JLabel("请输入您的姓名");
protected JTextField inputName=new JTextField(15);
protected JButton beginText=new JButton("开始测试");
protected Calendar date=Calendar.getInstance();//获取当期系统时间,作为计算人品你的依据
protected int year=date.get(Calendar.YEAR);
protected int month=date.get(Calendar.MONTH)+1;
protected int day=date.get(Calendar.DATE);
public TextGraphics(){
super("Text Graphics");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(300, 20, 600, 500);
this.setVisible(true);
this.addPanel();
this.beginText.addActionListener(this);
this.add(panel);
}
private void addPanel(){
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));//设置布局管理器
panel.add(label);
panel.add(displayArea);
panel.add(info);
panel.add(inputName);
panel.add(beginText);
}
protected int calcRP(String str){
char[] name=str.toCharArray();
int sum=0;
for(int i=0;i<name.length;i++){
sum+=name[i];
}
//人品计算公式:年+月+日+SUM(姓名)%100
sum+=year+month+day;
sum%=100;
return sum;
}
protected void showRP(){
String name=inputName.getText();
if (name==null || name.equals("")){
JOptionPane.showMessageDialog(this, "请输入合法姓名,不要挑战人品测试器的权威!!");
return;
}
inputName.setText("");
displayArea.setText(name+"\n"+"您"+year+"年"+month+"月"+day+"日"+"的人品是"+"\n"+calcRP(name));
}
public void actionPerformed(ActionEvent arg0) {
beginText.setText("重新测试");
showRP();
}
public static void main(String[] args) {
TextGraphics tg=new TextGraphics();
}
}