Reputation: 2708
I am new to learning Java.
I am creating a JInternalFrame which have 28 labels in matrix forms in it. I want to change label text from - to + on click & vice versa.
I can do it adding EventListeners to each label one by one. But I want some simple solution in which I don't need to add eventlisteners for each label individually. A long ago I have tried same methodology on array of buttons in VisualBasic.
Upvotes: 0
Views: 41
Reputation: 324167
But I want some simple solution in which I don't need to add eventlisteners for each label individually
Why? You can share the MouseListener. Then you just add the listener to the label when you create the label. This is the better approach then trying to search for the clicked label after the fact.
For example:
MouseListener ml = new MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
JLabel label = (JLabel)e.getComponent();
label.setText( label.getText().equals("-") ? "+" : "-" );
}
}
for (int i = 0; i < 28)
{
JLabel label = new JLabel("-");
label.addMouseListener( ml );
panel.add(label);
}
Upvotes: 4