event

PropertyChangeListener example

In this tutorial we are going to see how to use PropertyChangeListener in Java. This is very important when you are working with many components and you want to have full control over their properties.

Another use case of this Listener might be when you want to customize the behavior of your program according to the changes of certain properties of your components.

In short all you have to do to work with PropertyChangeListener is :

  • Create a new PropertyChangeListener instance.
  • Override the propertyChange event in order to customize the handling of the specific event.
  • You can use Event.getPropertyName() method to handle differently, specific properties of the component.
  • Use Event.getNewValue() to get the new value of a certain property that has changed
  • Use addPropertyChangeListener to add the PropertyChangeListener to the component you want.

Let’s see the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {

    public static void main(String args[]) {

  JFrame frame = new JFrame("Button Sample");

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  final JButton button1 = new JButton("Press me");

  final JButton button2 = new JButton("Press me");

  ActionListener actionListener = new ActionListener() {

@Override

public void actionPerformed(ActionEvent actionEvent) {

    JButton jButton = (JButton) actionEvent.getSource();

    int r = (int) (Math.random() * 100);

    int g = (int) (Math.random() * 100);

    int b = (int) (Math.random() * 100);

    jButton.setBackground(new Color(r, g, b));

}

  };

  PropertyChangeListener propChangeListn = new PropertyChangeListener() {

@Override

public void propertyChange(PropertyChangeEvent event) {

    String property = event.getPropertyName();

    if ("background".equals(property)) {

  button2.setBackground((Color) event.getNewValue());

    }

}

  };

  button1.addActionListener(actionListener);

  button1.addPropertyChangeListener(propChangeListn);

  button2.addActionListener(actionListener);

  Container cPane = frame.getContentPane();

  cPane.add(button1, BorderLayout.NORTH);

  cPane.add(button2, BorderLayout.SOUTH);

  frame.setSize(500, 300);

  frame.setVisible(true);
    }
}

 
This was an example on how to use PropertyChangeListener in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button