【问题标题】:show letters when mouse move on letters当鼠标移到字母上时显示字母
【发布时间】:2016-11-12 04:43:28
【问题描述】:
我有 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)
{
}
谢谢!!!
【问题讨论】:
标签:
java
swing
user-interface
【解决方案1】:
使用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);
});
}
}