gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:38:21 24 4
gpt4 key购买 nike

根据我之前的问题: 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”标题的按钮都会消失(这已经发生了)

最佳答案

按照@Freddy的答案使用集合应该会更好。然而,如果你坚持使用数组,像下面这样的东西应该可以做到(虽然还没有测试过)

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

关于java - 禁用 JAVA 上的按钮,但保留唯一的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54866902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com