0

My program is supposed to when a button is clicked, remove it and replace it with a label. In my program, the button is removed when clicked, but the label isnt added until another button is clicked, which removes hat button but then that label doesnt show.... and so on. Here is the code:

//adds buttons to screen if corresponding
//boolForButtons is true, else it
//displays label
public void addButtons() {
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            if (boolForButtons[i][j]) {
                add(buttons[i][j]);
            } else {
                remove(buttons[i][j]);
                add(labels[i][j]);
            }
        }
    }
}

//refreshs the screen
public void refreshButtons() {
    revalidate();
    repaint();

    addButtons();
}

//if button is clicked
public class event implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        for (int i = 0; i < 10; i++) {
            for (int j = 0; j < 10; j++) {
                //set the button clicked to not show on the screen
                if (e.getSource() == buttons[i][j]) {
                    boolForButtons[i][j] = false;
                }
            }
        }

        refreshButtons();
    }
}

thanks -

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Derek Schuster
  • 523
  • 1
  • 6
  • 14
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) For many components in one space, use a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) as seen in this [short example](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Nov 24 '13 at 16:24

3 Answers3

1

Try to call repaint() after the call off addButtons(). In your code the label is added after you repaint the component.

 public void refreshButtons() {
      addButtons();
      revalidate();
      repaint();
  }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
G_J
  • 314
  • 3
  • 6
1

You should call revalidate and repaint after add the buttons. Change your method position.

//refreshs the screen
public void refreshButtons() {
    addButtons();  // Add button here.
    revalidate();
    repaint();   
}
Masudul
  • 21,823
  • 5
  • 43
  • 58
1

If I were trying to accomplish something similar I would look into CardLayout:

http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

From: http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html

A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.

umhelp
  • 175
  • 8