2016-07-09 1 views
0

나는 JTextField를 가지고 있고 그것을 mousemotionListener에 추가했다. 이 편지에 마우스를 올려 놓으면 편지를 받고 싶습니다. 그러나 나는 어떻게 이런 일을 할 수 있는지 모르겠다. 그리고 나는 그 편지를 어떻게 얻을 수 있는지 모른다.편지를 마우스로 움직일 때 글자 표시

다음은 내 코드

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 
import javax.swing.border.*; 
public class SetText extends JPanel implements MouseMotionListener 
{ 

    JTextField text; 

    public SetText() 
    { 
    text = new JTextField(10); 
    text.addMouseMotionListener(this); 
    add(text); 
    } 

    public void mouseMoved(MouseEvent e) 
    { 
    int x = e.getX(); 
    int y = e.getY(); 

    String str = text.getText(x,y); 
    } 

    public void mouseDragged(MouseEvent e) 
    { 

    } 

당신을 감사에게있다!

+0

(http://stackoverflow.com/a/5957405/714968) – mKorbel

답변

4

JTextComponent의 viewToModel(Point p) 메서드를 사용하면 텍스트 문서에서 위치를 가져올 수 있습니다. 예를 들어 ... [예]

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 

public class SetText extends JPanel implements MouseMotionListener { 

    private static final float POINTS = 40f; 
    JTextField textField; 
    private JLabel displayLabel = new JLabel("   ", SwingConstants.CENTER); 

    public SetText() { 
     textField = new JTextField("Hello world! How's it going?", 20); 
     textField.addMouseMotionListener(this); 

     // make the text bigger so easier to test 
     textField.setFont(textField.getFont().deriveFont(Font.BOLD, POINTS)); 

     JLabel lbl = new JLabel("Text:"); 
     lbl.setFont(lbl.getFont().deriveFont(Font.BOLD, POINTS)); 
     displayLabel.setFont(displayLabel.getFont().deriveFont(Font.BOLD, POINTS)); 

     JPanel centerPanel = new JPanel(); 
     centerPanel.add(lbl); 
     centerPanel.add(displayLabel); 

     setLayout(new BorderLayout()); 
     add(textField, BorderLayout.PAGE_START); 
     add(centerPanel, BorderLayout.CENTER); 
    } 

    public void mouseMoved(MouseEvent e) { 
     int location = textField.viewToModel(e.getPoint()); 

     String text = textField.getText(); 
     if (text.isEmpty()) { 
      return; 
     } 
     // if (location > 0 && location < text.length()) { 
     if (location >= 0 && location < text.length()) { 
      char c = textField.getText().charAt(location); 
      displayLabel.setText(String.valueOf(c)); 
     } else if (location >= text.length()) { 
      displayLabel.setText(text.substring(text.length() - 1)); 
     } 
    } 

    public void mouseDragged(MouseEvent e) { 

    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> { 
      JFrame frame = new JFrame("Set Text"); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.add(new SetText()); 
      frame.pack(); 
      frame.setLocationRelativeTo(null); 
      frame.setVisible(true); 
     }); 
    } 
} 
+0

감사합니다 아주 많이, 다 괜찮 그것은 작동합니다. – GhostDede

관련 문제