【发布时间】:2016-08-31 23:03:26
【问题描述】:
我正在编写一个程序,我需要根据单击的按钮为单独的类执行不同的操作。
public class NewJFrame{
public static JButton b1;
public static JButton b2;
public static JButton b3;
}
public class Slot{
int value;
JButton button;
Slot(int value, JButton button)
{
this.value=value;
this.button=button;
}
}
public class Game{
Slot[] slots=new Slot[3];
Game(){
slots[0]=new Slot(1,NewJFrame.b1);
slots[1]=new Slot(2,NewJFrame.b2);
slots[2]=new Slot(3,NewJFrame.b3);
}
public void actionPerformed(ActionEvent e) {
for(int i=0;i<3;i++){
if(e.getSource()==slots[i].button)
slots[i].button.setText(String.valueOf(value));
}
}
}
类似的东西。请注意,我在 GUI 设计方面完全是新手。
【问题讨论】:
-
请提出更具体的问题。到目前为止,您所做的只是发布一些模糊的过于宽泛的要求。你的问题越具体,答案通常就越好、越具体。请查看help center 和how to ask good questions 部分,了解有关如何改进您的问题并增加获得体面帮助的机会的更多信息。
-
不相关的记录:以上字段都不应该是静态的,尤其是 JButtons。类名应以大写字母开头以符合 Java 命名约定,因为如果您这样做,其他人会更好地理解您的代码和您的问题。
-
感谢您的更名,但更重要的更正是改进您的问题,使其更易于理解和回答。
-
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
-
你“解决”这个问题的方式与你应该做的完全相反。正确的解决方案是不要以静态方式访问这些按钮。不过,您仍然没有澄清您的主要问题。
标签: java swing user-interface awt