禁用JAVA上的按钮,但不保留唯一按钮

时间:2019-02-25 13:05:24

标签: java awt

根据我之前在这里的问题: Remove a Button with same text when clicked

我只需要出现更多的按钮,然后单击它们就会消失 问题是,单击“唯一”图标(参见图片)时,它们也会消失。 我的代码:

private String namesArr[] = {"Yakir","Yarden","Igor","Maoz","Moshe","Israel","Tal","Haim","Nati","Mor","Daniel","Idan"};
private Button buttonArr[] = new Button[namesArr.length];
private Font font;

public StudentsGUI(String caption) {
    super(caption);
    addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                    dispose();
                        System.exit(0);
                        }
                    }); 
    this.setLayout(new GridLayout(3,3));
    font = new Font("Ariel",Font.BOLD,35);

    for(int i=0;i<namesArr.length;i++) {
        buttonArr[i] = new Button(" "+namesArr[(int)(Math.random()*namesArr.length)]);
        buttonArr[i].setFont(font);
        buttonArr[i].addActionListener(this);
        this.add(buttonArr[i]);
    }
    setLocation(800,500);
    setVisible(true);
    pack();
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof Button) {
        String btnText = ((Button)e.getSource()).getLabel();
        for(int i=0; i<buttonArr.length; i++) {
            if (buttonArr[i].getLabel().equals(btnText)) {
                this.remove(buttonArr[i]);
                pack();
            }
        }
    }
}

可帮助您理解的图片: enter image description here 因此,如果单击“ Idan”将什么都不会发生,但是如果单击“ Maoz”,则带有“ Maoz”的所有按钮都将消失(这已经在发生)

2 个答案:

答案 0 :(得分:0)

您的意思是这样的(代码可能有语法错误)?

public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof Button) {
        String btnText = ((Button)e.getSource()).getLabel();

        List<Button> btnList = new ArrayList<Button>();
        for(int i=0; i<buttonArr.length; i++) {
            if (buttonArr[i].getLabel().equals(btnText)) {
                btnList.add(buttonArr[i]);
                //this.remove(buttonArr[i]);
                //pack();
            }
        }
        if (btnList.size() > 1) {
            for (Iterator<Button> it = btnList.iterator(); it.hasNext()) {
                this.remove(it.next());
            }
            pack();
        }
    }
}

答案 1 :(得分:0)

按照@Freddy的答案使用集合应该更好。但是,如果您要坚持使用数组,则应执行以下操作(尽管尚未测试)

select array_agg(a.c order by a.idx)
from unnest(string_to_array('a__b___d_','_')) with ordinality as a(c,idx)
where nullif(trim(c), '') is not null;