I have this situation, where I would like to display a number in figures. The number will be entered onto a Jtextfield and I would like the tooltip to display the amount in figures. The problem is, the tooltip displays the older data.
I have written some code to show you the issue:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test
{
public static void main(String[] args) {
final JFrame frame=new JFrame();
frame.setLayout(new FlowLayout());
frame.setPreferredSize(new Dimension(400,100));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField tf=new JTextField(30);
frame.add(tf);
frame.add(new JTextField(30));
tf.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e) {
tf.setToolTipText(tf.getText());
}
@Override
public void focusGained(FocusEvent e) {
tf.setToolTipText(tf.getText());
}
});
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.pack();
frame.setVisible(true);
}
});
}
}
Let’s take this situation, the user is typing number onto the first textfield. The text cursor is still on the same textfield. When the user now moves the mouse pointer over the first textfield, the tooltip is still displaying the old text.
Now when you shift the focus to the second textfield, the first textfield’s data gets committed so the tooltip also refreshes.
Now how do I display the tooltip on the text that is still not committed in a textfield?
If you want to update the tooltips each time the user types something, you should add a
DocumentListenerto theDocumentof yourJTextField, which can be retrieved using theJTextField#getDocument.The Swing tutorial has an example of such a
DocumentListener