0

I have a main JPanel that's called board which has another JPanel in it with two `JButtons' one of which is supposed to remove this panel when clicked.

public class AditWindow extends JPanel {
    private int width;
    private int height;

public AditWindow(int x, int y){
        super();
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        width=180;
        height=60;
        setBounds(x, y, width, height);
        JButton addLoc = new JButton("Add Location");
        JButton addSign = new JButton("Add Sign");
        addLoc.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                close();
                System.out.println("click");
            }
        });
        addSign.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("addSign");
            }
        });
        Main.font=Main.font.deriveFont(13f);
        addLoc.setFont(Main.font);
        addSign.setFont(Main.font);
        addLoc.setMaximumSize(new Dimension(width, 30));
        addSign.setMaximumSize(new Dimension(width, 30));
        addLoc.setBackground(new Color(0xF6F6F6));
        addSign.setBackground(new Color(0xF6F6F6));
        add(addLoc);
        add(addSign);
        Main.board.validate();

private void close(){
        System.out.println("close");
        Main.board.del(this);
        }
}

The del method is:

public void del(Component c){
        remove(c);
        validate();
        System.out.println("removed");
        }

Problem is: for some reason it takes 2 clicks for the panel to get removed, but the lines get printed on both clicks. I am unsure how to properly manage this situation.

EIDT: If I remove the validate() line from the del() method it will work from the first click but only the buttons will dissapear leaving a rectangle background of the JPanel on the screen.

seMikel
  • 246
  • 2
  • 14

2 Answers2

0

You might try invoking the remove/validate within a SwingUtilities.invokeLater() call.

crig
  • 859
  • 6
  • 19
  • So something like this:`public void del(final Component c){ SwingUtilities.invokeLater(new Runnable() { public void run() { remove(c); validate(); System.out.println("removed"); } }); }` ? – seMikel Jul 17 '15 at 16:24
  • Yes, that's correct. Could also be the problem that you are calling validate(). You might want revalidate() instead. Or even repaint().. Check this for more info: https://stackoverflow.com/questions/1097366/java-swing-revalidate-vs-repaint – crig Jul 20 '15 at 15:12
0

try passing AditWindow.this to the Main.board.del() method instead of this.