Skip to main content

Cursor issues in JTextarea

No replies
arka.sharma
Offline
Joined: 2011-07-26
Points: 0

Hi,

I want to create an linux terminal like interface using java swing.The fllowing code i have written.But i'm facing issues while pressing arrow keys in textarea.Please run this code to understand the problem.

  1. package poc.gui;
  2. import java.awt.Color;
  3. import java.awt.Graphics;
  4. import java.awt.Rectangle;
  5. import javax.swing.JFrame;
  6. import javax.swing.JTextArea;
  7. import javax.swing.plaf.TextUI;
  8. import javax.swing.text.BadLocationException;
  9. import javax.swing.text.DefaultCaret;
  10. import javax.swing.text.JTextComponent;
  11. public class CaretDemo extends JFrame
  12. {
  13. JTextArea area=null;
  14. CaretDemo()
  15. {
  16. setSize(400,400);
  17. area = new JTextArea();
  18. area.setCaret(new NewCaret());
  19. add(area);
  20. }
  21. public static void main(String[] args) {
  22. // TODO Auto-generated method stub
  23. CaretDemo dc = new CaretDemo();
  24. dc.setVisible(true);
  25. }
  26. }
  27. class NewCaret extends DefaultCaret
  28. {
  29. protected void damage(Rectangle r)
  30. {
  31. //System.out.println("damage : x="+x+", y="+y+", height="+height+", width="+width+", dot="+getDot()+", mark="+getMark());
  32. //super.damage(r);
  33. if(r!=null)
  34. getComponent().repaint(r.x,r.y,8,r.height);
  35. }
  36. public void paint(Graphics g)
  37. {
  38. //super.paint(g);
  39. g.setColor(Color.GREEN);
  40. JTextComponent comp = getComponent();
  41. Rectangle rec = null;
  42. TextUI ui = comp.getUI();
  43. try {
  44. rec = ui.modelToView(comp, getDot());
  45. } catch (BadLocationException e) {
  46. // TODO Auto-generated catch block
  47. e.printStackTrace();
  48. }
  49. g.fillRect(rec.x, rec.y, 8, rec.height);
  50. }
  51. } //Help is expected