import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Exec69 extends JFrame{ JTextField text; JTextArea re; JLabel label; public Exec69() { setSize(400,400); setTitle("Exec69"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); text = new JTextField(20); text.addKeyListener(new KeyLis()); re = new JTextArea(5,10); add(text,BorderLayout.NORTH); label = new JLabel(" "); add(label,BorderLayout.SOUTH); JScrollPane js = new JScrollPane(re); js.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); add(js); setVisible(true); pack(); } /** * @param args */ public static void main(String[] args) { new Exec69(); } private long getSum(long s) { long ret = 0; for(long i=1;i<=s;i++) ret+=i; return ret; } class KeyLis extends KeyAdapter { StringBuilder str = new StringBuilder(); public void keyPressed(KeyEvent e) { if ((e.getKeyCode()>=KeyEvent.VK_0)&&(e.getKeyCode()<=KeyEvent.VK_9)) { //System.out.println(e.getKeyChar()); str.append(e.getKeyChar()); } else if(e.getKeyCode()==KeyEvent.VK_ENTER) { String s = str.toString(); if (s.equals("")) s="0"; final long num = Long.valueOf(s); new Thread(new Runnable(){ public void run(){ re.setText(String.valueOf(getSum(Long.valueOf(num)))); label.setText("1-"+num+"的和"); } }).start(); //label.setText(String.valueOf(getSum(Long.valueOf(num)))); str = new StringBuilder(); text.setText(""); } else { text.setText(""); text.setText("输入错误!!"); str = new StringBuilder(); } } } }