2013-09-22 6 views
1

사실, 이미이 질문을 here에 묻습니다. 그러나, 나는 실수하고있다. 나는 아직 해결책을 얻지 못했다.JTextArea에서 캐럿 위치의 XY 위치 가져 오기

첫째, 이전의 질문에, 내가

Rectangle rectangle = textArea.modelToView(textArea.getCaretPostion()); 

으로 사각형을 얻을 수있는 I 해요 또한 X 및 Y 위치를 얻는다.

나는 각각 새로운 텍스트 영역을 추가 할 수있는 편집기를 만들고 있는데, Enter 키를 누릅니다. 위의 코드가있는 XY 위치는 항상 모든 텍스트 영역에서 동일한 반환 값을 제공합니다. 내 코드를 봐.

import java.awt.Container; 
import java.awt.Font; 
import java.awt.Rectangle; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import java.util.LinkedList; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.AbstractAction; 
import javax.swing.Action; 
import javax.swing.Box; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 
import javax.swing.KeyStroke; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.JTextComponent; 

public class forquestion extends JFrame { 

    Container textAreaBox; 
    LinkedList<JTextComponent> textArea; 
    int nameTA; 

    public forquestion() { 
      int nameTA = 0; 

      textArea = new LinkedList<>(); 

      textAreaBox = Box.createVerticalBox(); 
      textAreaBox.add(Box.createVerticalGlue()); 
      addLine(); 
      this.add(textAreaBox); 
      this.setVisible(true); 
    } 

    public static void main(String[] args) { 
      forquestion app = new forquestion(); 
      app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public void addLine() { 

      JTextComponent temp_ta = createTextComponent(); 
      textArea.add(temp_ta); 
      textAreaBox.add(textArea.getLast()); 
      textAreaBox.add(Box.createVerticalGlue()); 
    } 

    protected JTextComponent createTextComponent() { 
      JTextArea ta = new JTextArea("test"); 

      /*if (count%2==0) 
          ta.setForeground(Color.red); 
      else 
          ta.setForeground(Color.GREEN);*/ 

      ta.setFont(new Font("Courier New",Font.PLAIN,16)); 
      ta.setLineWrap(true);                                                             
      ta.setWrapStyleWord(true); 
      ta.setName(Integer.toString(nameTA)); 
      nameTA+=1; 

      basicKey("ENTER", enter, ta); 

      ta.addMouseListener(new java.awt.event.MouseAdapter() { 
        public void mousePressed(java.awt.event.MouseEvent ev) { 
          try { 
            taMousePressed(ev); 
          } catch (BadLocationException ex) { 
            Logger.getLogger(forquestion.class.getName()).log(Level.SEVERE, null, ex); 
          } 
        } 
      }); 

      return ta; 
    } 

    public void basicKey(String s, Action a, JTextArea ta) { 

      ta.getInputMap().put(KeyStroke.getKeyStroke(s), s); 
      ta.getActionMap().put(s, a); 
    } 

    Action enter = new AbstractAction() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 

        addLine(); 
      } 
    }; 

    private void taMousePressed(java.awt.event.MouseEvent ev) throws BadLocationException { 
      int now_focus = Integer.parseInt(ev.getComponent().getName()); 
      int _caret; 
      _caret = textArea.get(now_focus).getCaretPosition(); 
      Rectangle rectangle = textArea.get(now_focus).modelToView(_caret); 
      double x = rectangle.getX(); 
      //int xc = textArea.get(now_focus).getLocation().x; 
      double y = rectangle.getY(); 
      //int yc = textArea.get(now_focus).getLocation().y; 
      //double h = rectangle.getHeight(); 
      //double w = rectangle.getWidth(); 
      System.out.println(x); 
      System.out.println(y); 
      //System.out.println(xc); 
      //System.out.println(yc); 
      //System.out.println(h); 
      //System.out.println(w); 
      System.out.println(""); 
    } 

} 

텍스트 영역을 누를 때마다 내 코드가 XY 위치를 인쇄합니다. 그러나 디스플레이는 모든 텍스트 영역에서 항상 동일합니다. (많은 텍스트 영역을 만들고 텍스트를 입력하십시오) Btw, 그냥 간단한 코드. Enter 키를 누르면 새 텍스트 영역을 업데이트하기 위해 창 프레임 크기를 변경해야합니다. 하하하.

내 질문은 : 어떻게 텍스트 영역에서 캐럿 (텍스트 커서)의 XY 위치를 얻을 수 있습니다. 거기에 JPopmenu를 표시하고 싶습니다. :)

나는이 질문이 당신에게 분명 희망이된다. 전에 Thx.

답변

3

Rectangle은 텍스트 영역을 기준으로 한 상대 위치이며, 여기서 0x0 위치는 구성 요소의 왼쪽 위 모서리입니다. 당신이 뭔가를 사용하는 경우

... popupJPopupMenu입니다

popup.show(textArea.get(now_focus), rectangle.x, rectangle.y + rectangle.height); 

, 그것은 화면 자체에 필요한 번역을 할 것입니다.

지금. 라고 한. 개인적으로 저는 Swing에서 제공하는 팝업 API 지원을 사용하는 것을 선호합니다. 이것은 ... 그것을 달성하기 위해 JTextArea에서 확장하는 사용자 정의 구성 요소를 만들 필요가 의미하는 것입니다

public class MyPopupTextArea extends JTextArea { 
    /*...*/ 
    public Point getPopupLocation(MouseEvent evt) { 
     Rectangle rectangle = textArea.get(now_focus).modelToView(_caret); 

     Point p = rectangle.getLoction(); 
     p.y += rectangle.height; 

     return p; 
    } 
} 

그런 다음, 필요에 따라, 당신은 JPopupMenu 또는 공유 인스턴스를 제공하기 위해 setComponentPopup를 사용할 수있는 경우 필수, 사용자 정의 편집기의 각 인스턴스에 대해 사용자 정의 JPopupMenu을 작성하고 적합하다고 판단되면 setComponentPopup을 사용하십시오.

+0

참조하십시오. 솔루션을위한 Thx .Btw, 내 문제에 대한 전체 코드를 줄 수 있습니까? 최소한 패널 또는 프레임에 Jpopmenu를 추가하기위한 코드 또는 코드의 생성자. 나는 아직도 JPopMenu를 배우고있다. 컨테이너에 추가 할 때마다 다른 구성 요소를 포함합니다. – TblsX

+0

구성 요소 (일반적으로)에 JPopupMenu를 추가하지 마십시오. setComponentPopup을 사용하여 팝업을 구성 요소와 연관 시키거나 특별한 필요가있는 경우 JPopupMenu # show를 사용하여 팝업을 표시해야합니다. 특수 창과 유사한 구성 요소를 생각해보십시오. 자세한 내용은 [팝업 메뉴 설정하기] (http://docs.oracle.com/javase/tutorial/uiswing/components/menu.html#popup)를 참조하십시오 ... – MadProgrammer

+0

나에게 의미가 있습니다. 어쨌든 고마워요 : D – TblsX