Reputation: 1521
I am building a program in java and I was wondering if there is any function to remove a a list of JButtons when on is pressed?
This is what I have so far:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button[0]) {
for(int x = 0; x < 19; x++) {
button[x].remove(this);
}
}
}
ActionListener is already configure and it works fine. Thank you in advance for who ever gives me a solution.
Upvotes: 0
Views: 157
Reputation: 2296
image 1) JButton b[]=new JButton[10];
for(int i=0;i<10;i++)
{
b[i]=new JButton(""+i);
b[i].setBounds(i*10,i*20,20,20);
add(b[i]);
}
b[0].addActionListener(this);
adding Buttons on Frame and setting Action Listenr to b[0] button.
image 2) public void actionPerformed(ActionEvent e) {
if(e.getSource() == b[0]) {
for(int 1 = 0; 1 < 5; 1++) {
remove(b[x]);
}
}
}
1) The First image adding buttons on Frame 2) The Second image Remove Buttons on Frame.
Upvotes: 0
Reputation: 4704
Try this:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button[0]) {
for(int x = 0; x < 19; x++) {
button[x].getParent().remove(button[x]);
}
}
}
Upvotes: 2
Reputation: 285460
Your current code looks to be trying to remove something, your this
, whatever it represents, from the JButton, which is bassackwards.
The key information to tell is -- remove the button from what? If a JPanel, then you must do just this, call remove(...)
on the containing JPanel, passing in the component (the JButton) that you want to remove.
i.e.,
public void actionPerformed(ActionEvent e) {
containingJPanel.remove((AbstractButton) e.getSource());
}
The specific code solution will depend on the structure of your current program.
Upvotes: 5