create a simple java bean having bound and constrained properties

Solutions on MaxInterview for create a simple java bean having bound and constrained properties by the best coders in the world

showing results for - "create a simple java bean having bound and constrained properties"
Erick
09 Mar 2017
1import java.awt.Graphics;
2import java.beans.PropertyChangeListener;
3import java.beans.PropertyChangeSupport;
4import java.io.Serializable;
5import javax.swing.JComponent;
6
7/**
8 * Bean with bound properties.
9 */
10public class MyBean
11        extends JComponent
12        implements Serializable
13{
14    private String title;
15    private String[] lines = new String[10];
16
17    private final PropertyChangeSupport pcs = new PropertyChangeSupport( this );
18
19    public String getTitle()
20    {
21        return this.title;
22    }
23
24    public void setTitle( String title )
25    {
26        String old = this.title;
27        this.title = title;
28        this.pcs.firePropertyChange( "title", old, title );
29    }
30
31    public String[] getLines()
32    {
33        return this.lines.clone();
34    }
35
36    public String getLines( int index )
37    {
38        return this.lines[index];
39    }
40
41    public void setLines( String[] lines )
42    {
43        String[] old = this.lines;
44        this.lines = lines;
45        this.pcs.firePropertyChange( "lines", old, lines );
46    }
47
48    public void setLines( int index, String line )
49    {
50        String old = this.lines[index];
51        this.lines[index] = line;
52        this.pcs.fireIndexedPropertyChange( "lines", index, old, lines );
53    }
54
55    public void addPropertyChangeListener( PropertyChangeListener listener )
56    {
57        this.pcs.addPropertyChangeListener( listener );
58    }
59
60    public void removePropertyChangeListener( PropertyChangeListener listener )
61    {
62        this.pcs.removePropertyChangeListener( listener );
63    }
64
65    protected void paintComponent( Graphics g )
66    {
67        g.setColor( getForeground() );
68
69        int height = g.getFontMetrics().getHeight();
70        paintString( g, this.title, height );
71
72        if ( this.lines != null )
73        {
74            int step = height;
75            for ( String line : this.lines )
76                paintString( g, line, height += step );
77        }
78    }
79
80    private void paintString( Graphics g, String str, int height )
81    {
82        if ( str != null )
83            g.drawString( str, 0, height );
84    }
85}
86
87