写了一个程序,需要按回车就停止打印,再按回车继续打印。 方法一:用线程: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class MyTyper implements Runnable { static boolean flag; private String text; /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub flag = true; MyTyper typer1 = new MyTyper("I am a typer"); Thread thread = new Thread(typer1); thread.start(); while (true){ // Scanner sc=new Scanner(System.in); BufferedReader br =new BufferedReader(new InputStreamReader(System.in)); // if (sc.hasNext()){ if (br.read()>0){ if (flag == true){ flag = false ; } else flag = true; } } } public MyTyper(String text){ this.text = text; } @Override public void run() { while (true){ if (flag) System.out.println(text); } } } 方法二:用swing,可是这种方法现在还存在一定问题,没有实现这个功能,现在先这么写着吧,回头再好好看看。 import java.awt.HeadlessException; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; import javax.swing.JTextArea; public class MyTyper2 extends JFrame implements KeyListener { JTextArea textArea; static boolean flag=true; public MyTyper2() { textArea=new JTextArea(); textArea.setEditable(false); this.add(textArea); this.setVisible(true); this.setSize(300, 300); addKeyListener(this); } public static void main(String args[]) { MyTyper2 typer=new MyTyper2(); int i=0; while(flag) { typer.textArea.setText("number:"+i++); } } public void keyPressed(KeyEvent e) { if(e.getKeyCode()==e.VK_ENTER) { if(flag==true) { flag=false; } else flag=true; } else flag=true; } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }