因此,我试图让 DriverPC 类知道何时按下框架对象中的按钮,以便它可以使用 DoThis() 方法,但不确定如何处理这种情况。
DriverPC 类:
public class DriverPC {
private static void DoThis(){
//Send information through already set up datastream when button in Frame clicked
}
public static void main(String args[]){
//set up bluetooth datastream
communications();
//create gui
new Frame(200,200,200,200);
}
}
框架类:
public class Frame extends JFrame implements ActionListener{
JPanel pane = new JPanel();
JButton butt = new JButton("Button");
Frame(int a,int b,int c, int d){
super("My Simple Frame");
setBounds(a,b,c,d);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
butt.addActionListener(this);
con.add(pane);
pane.add(butt);
setVisible(true);
}
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if (source == butt){
}
}
}
只是想知道是否可能,如果不可能我该怎么做?
最佳答案
用线
butt.addActionListener(this);
在您的 Frame
构造函数中,您将按钮按下事件委托(delegate)给方法 Frame.actionPerformed
。
由于您的 DoThis
方法被声明为静态,您可以简单地在该方法中调用它:
public void actionPerformed(ActionEvent event){
Object source = event.getSource();
if (source == butt) {
DriverPC.DoThis();
}
}
要实现此功能,DoThis
方法也必须是公共(public)的(或者至少是包私有(private)的,我猜):
public static void DoThis() {
System.out.println("Awesome");
}
现在,每当您按下按钮时,输出都会打印在控制台中。
顺便说一句:请遵守Java代码约定,方法名称以小写字母开头:
public static void doThis() { ... }
关于Java:如何让对象监听器在不同的类中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26355776/