标签:
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 public class Test_16_10 extends JFrame{ 6 public Test_16_10(){ 7 JP jp1 = new JP(); 8 add(jp1); 9 jp1.setFocusable(true); 10 } 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 Test_16_10 t1 = new Test_16_10(); 15 t1.setSize(300,400); 16 t1.setTitle("Test_16_10"); 17 t1.setLocationRelativeTo(null); 18 t1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19 t1.setVisible(true); 20 } 21 22 static class JP extends JPanel{ 23 private StringBuffer str = new StringBuffer(); 24 private String str1 = "A"; 25 private int x,y; 26 27 public JP(){ 28 addKeyListener(new KeyAdapter(){ 29 public void keyTyped(KeyEvent e){ 30 str.append(e.getKeyChar()); 31 } 32 public void keyPressed(KeyEvent e){ 33 if(e.getKeyCode() == KeyEvent.VK_ENTER) 34 str1 = str.toString().trim(); 35 str.setLength(0);//将stringbuffer重置为空 36 repaint(); 37 } 38 }); 39 } 40 protected void paintComponent(Graphics g){ 41 x = getWidth()/2; 42 y = getHeight()/2; 43 super.paintComponent(g); 44 g.drawString(str1, x, y); 45 } 46 } 47 }
效果图:
标签:
原文地址:http://www.cnblogs.com/wanjiang/p/5641976.html