简体   繁体   English

Java-标签添加/按钮删除

[英]Java - Label adding/Button Removing

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 - 谢谢 -

Try to call repaint() after the call off addButtons(). 尝试取消addButtons() 之后调用repaint()。 In your code the label is added after you repaint the component. 在代码中,重新绘制组件后即添加了标签。

 public void refreshButtons() {
      addButtons();
      revalidate();
      repaint();
  }

You should call revalidate and repaint after add the buttons. 添加按钮后,您应该调用revalidaterepaint Change your method position. 更改方法位置。

//refreshs the screen
public void refreshButtons() {
    addButtons();  // Add button here.
    revalidate();
    repaint();   
}

If I were trying to accomplish something similar I would look into CardLayout: 如果我想完成类似的事情,我将研究CardLayout:

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

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

A CardLayout object is a layout manager for a container. CardLayout对象是容器的布局管理器。 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. 首次显示容器时,添加到CardLayout对象的第一个组件是可见组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM