There are 2 sets of 4 buttons being created.
The ImageIcon
of the 1st set of buttons are to be dragged onto the 2nd set of buttons.
The boolean enab
variable is for determining if the 2nd set of 4 buttons are enabled or not. I initially set the boolean to false, only when the ImageIcon
from the 1st set of buttons are dragged over, will the enab
value change to true.
However, the 2nd set of buttons remain disabled while and after I dragged the images over to it.
I inserted System.out.println
statements to see where did it go wrong, the result is that the enab
variable is updated but the stateChanged method doesn't run at all.
How do I get the stateChanged
method to detect that the buttons it listens to are already enabled for it run ?
private boolean enab = false;
// creates 4 buttons
for(int a=0; a<4; a++){
button[a] = new JButton(new ImageIcon(img)); // any img
TransferHandler transfer = new TransferHandler("icon");
button[a].setTransferHandler(transfer);
button[a].addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
JButton button = (JButton)e.getSource();
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
name1 = e.getComponent().getName();
System.out.println(name1);
enab = true;
System.out.println("enabled0:" + enab); // prints true
}
}
}
// adds the 4 buttons to panel
leftg.add(button[a]);
// creates another 4 buttons for stuff to be dragged to
for(int b=0; b<4; b++){
rg[b] = new JButton();
id2 += Integer.toString(++cc2);
// unique name for each button as an ID
rg[b].setName(id2);
TransferHandler transfer1 = new TransferHandler("icon");
rg[b].setTransferHandler(transfer1);
rg[b].setEnabled(enab);
System.out.println("enabled00:" + enab); // prints false
ChangeListener clistener = new ChangeListener(){
public void stateChanged(ChangeEvent ce) {
JButton source = (JButton)ce.getSource();
ButtonModel mod = source.getModel();
System.out.println("enabled1:" + enab); // no output
if (mod.isEnabled()){
System.out.println("enabled2:" + enab); // no output
if(name1 == source.getName()){
}
else{
source.setIcon(null);
}
}
else{
}
};
};
rg[b].addChangeListener(clistener);
// adds the 4 buttons to panel
rightg.add(rg[b]);
}