Jux*_*hin 3 java user-interface constructor jbutton getter-setter
我遇到了一个问题,因为我对GUI比较陌生。
基本上让每个人都参与其中,我有一个软件包,其中包括:
MainClass(包括GUI)所以我的MainClassGUI基本上是控制器。
但是,老实说,我不知道如何去做。被告知必须创建一个构造函数并使用getter / setter方法?但是,我仍然不知道如何调用该特定的类,而将另一类保持为“ Turned off”。
谢谢。
嗯,有很多方法可以做到这一点……要么为每个按钮创建匿名侦听器,然后根据您想要执行的操作,触发其他类中的方法或类似方法。
JButton b1 = new JButton();
b1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//Do something!
OtherClass other = new OtherClass();
other.myMethod();
}
});
JButton b2 = new JButton();
b2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//Do something else!
...
}
});
Run Code Online (Sandbox Code Playgroud)
另外,您可以使用命令字符串并关联一个唯一的命令(最好是最终命令),以便在接收到一个在公共侦听器实现中执行的action时与之进行比较;
//In your class, somewhere...
public final static String CMD_PRESSED_B1 = "CMD_PRESSED_B1";
public final static String CMD_PRESSED_B2 = "CMD_PRESSED_B2";
//Create buttons
JButton b1 = new JButton();
JButton b2 = new JButton();
//Assign listeners, in this case "this", but it could be any instance implementing ActionListener, since the CMDs above are declared public static
b1.addActionListener(this);
b2.addActionListener(this);
//Assign the unique commands...
b1.setActionCommand(CMD_PRESSED_B1);
b2.setActionCommand(CMD_PRESSED_B2);
Run Code Online (Sandbox Code Playgroud)
然后,在您的侦听器实现中;
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals(CMD_PRESSED_B1)
{
//Do something!
OtherClass other = new OtherClass();
other.myMethod();
}
else if (e.getActionCommand().equals(CMD_PRESSED_B2)
{
//Do something else!
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5964 次 |
| 最近记录: |