Reputation: 347
is there a way to delete a checkbox from it's current position?
E.g
1 - I have four checkboxes One, Two, Three and Four
2 - If I select checkbox Two and press delete button, checkbox Two will be removed and I want the checkbox Three to move up to checkbox Two position and checkbox Four to move up to checkbox Three position.
For now in my codes, I set the checkbox visibility to false after the checkbox Two is selected and delete button is press.
My desired output after checkbox Two is selected and delete button is pressed. checkbox Three to move up to checkbox Two position and checkbox Four to move up to checkbox Three position immediately.
my current codes
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CheckBoxTest {
JPanel panel = new JPanel(new GridLayout(0, 1));
JButton button = new JButton("Delete!");
String[] names = {"One", "Three","Four"};
JCheckBox[] checkboxes;
JFrame frame = new JFrame();
public CheckBoxTest() {
checkboxes = new JCheckBox[3];
for(int i = 0; i < names.length; i++) {
checkboxes[i] = new JCheckBox();
checkboxes[i].setText(names[i]);
panel.add(checkboxes[i]);
}
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
button.addActionListener(new btnActionPerformed());
}
public class btnActionPerformed implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < names.length; i++) {
if(checkboxes[i].isSelected()) {
System.out.println(checkboxes[i].getText() + " is deleted");
checkboxes[i].setVisible(false);
}
}
}
}
public static void main(String args[]) {
new CheckBoxTest();
}
}
Upvotes: 0
Views: 2466
Reputation: 559
Assuming that String[] names
also initially contains the value "Two" so you actually have 4 buttons, have you tried using JPanel's remove() and updateUI() method? Try adding:
checkboxes[i].setVisible(false); // line you have in your code, now
panel.remove(checkboxes[i]); // add this line
panel.updateUI(); // and this line
If you're going to remove something from the UI, you can't just setVisible to false; the component just becomes invisible. You have to actually remove it from the panel and then update it.
Upvotes: 3