Results 1 to 2 of 2

Thread: Label change event

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2003
    Location
    Porto Alegre, RS
    Posts
    210

    Label change event

    Anybody knows how can i get some event when the text of my label changes???

    Thank you,
    Guilherme

  2. #2
    Dazed Member
    Join Date
    Oct 1999
    Location
    Ridgefield Park, NJ
    Posts
    3,418
    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!");
      }
     }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width