Reputation: 2245
I'm trying to call method after changing text of JTextField.
textField.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent arg0)
{
System.out.println("IT WORKS");
panel.setPrice(panel.countTotalPrice(TabPanel.this));
}
public void insertUpdate(DocumentEvent arg0)
{
}
public void removeUpdate(DocumentEvent arg0)
{
}
});
When I call this method at another ActionListener, it works ok. But when I change text in text field, nothing happens. Even println. Any suggestions?
Upvotes: 6
Views: 14472
Reputation: 2654
Here is another solution to your problem. Instead of having to repeat the same code under each method, you could create a method and call that method for changedUpdate, insertUpdate, removeUpdate.
textField.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent arg0)
{
printMyLines();
}
public void insertUpdate(DocumentEvent arg0)
{
printMyLines();
}
public void removeUpdate(DocumentEvent arg0)
{
printMyLines();
}
private void printMyLines()
{
System.out.println("IT WORKS");
panel.setPrice(panel.countTotalPrice(TabPanel.this));
}
});
Upvotes: 0
Reputation: 11
I found this solution the fastest:
new JTextPane().addActionListener(new Key());
class Key extends KeyAdapter{
private static final Object lock = new Object();
private static int keydiff=0;
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode())
{
//IGNORE FUNCTIONAL KEYS
case 38 :
case 39 :
case 37 :
case 40 :
case 17 :
case 157 :
case 10 : break;
default : keydiff++;
}
if(keydiff!=0)
{
synchronized(lock){
keydiff=0;
//EVENT FIRED HERE
}
}
}
}
It's much faster than:
.getDocument().addDocumentListener( .... changeUpdate())
Upvotes: 0
Reputation: 2245
The problem solved. changedUpdated method called only when other atributes (font, size, but not text) changed. To call method after every change of text, I should put the call into insertUpdate and removeUpdate methods. This way:
textField.getDocument().addDocumentListener(new DocumentListener()
{
public void changedUpdate(DocumentEvent arg0)
{
}
public void insertUpdate(DocumentEvent arg0)
{
System.out.println("IT WORKS");
panel.setPrice(panel.countTotalPrice(TabPanel.this));
}
public void removeUpdate(DocumentEvent arg0)
{
System.out.println("IT WORKS");
panel.setPrice(panel.countTotalPrice(TabPanel.this));
}
});
Upvotes: 10
Reputation: 5811
Try using an ActionListener
:
textField.addActionListener(this);
...
public void actionPerformed(ActionEvent evt) {
String s = textField.getText();
System.out.println(s);
...
}
Upvotes: 1