There really is no event that is fired off(that i know of) when the text of a JLabel changes. JTextArea and JTextField fire off TextEvents when the contents of them are changed with textValueChanged(TextEvent) being invoked. It would have been nice if sun provided this same functionality with the JLabel class.
All i would do is compare the text value of the JLabel with the new value to see if they are different or not. Rather than have the JLabel fire off the event have the component that is changing the text value of the JLabel fire off an event.
Code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class X{
public static void main(String[] args){
JButton jb = new JButton("Change Label");
JFrame jf = new JFrame();
JLabel jl = new JLabel("What's up?", JLabel.CENTER);
Container c = jf.getContentPane();
c.add(jl,BorderLayout.NORTH);
c.add(jb,BorderLayout.SOUTH);
jf.setSize(400,300);
jf.setVisible(true);
jb.addActionListener(new ButtonListener(jl));
jf.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
}
class ButtonListener implements ActionListener{
JLabel jl;
boolean b;
LabelListener ll;
public ButtonListener(JLabel jl){
this.jl = jl;
ll = new LabelListener(jl);
}
public void actionPerformed(ActionEvent ae){
if(b){
ll.setLabel();
jl.setText("What's up");
b = false;
ll.compare();
}else{
ll.setLabel();
jl.setText("The Sky?");
b = true;
ll.compare();
}
}
}
class LabelListener{
JLabel jl;
String jltext;
public LabelListener(JLabel jl){
this.jl = jl;
}
public void setLabel(){
jltext = jl.getText();
}
public void compare(){
if(!jltext.equals(jl.getText()))
System.out.println("JLabel text has changed!");
}
}