所以我的程序包含两个类 1. 我的主类处理 GUI,它扩展了 JFrame 所以我需要实例化它来配置我的 JFrame 。2. MyClass,它使用 API 请求和处理从服务器请求的数据,该 API 必须有一个 API 类的实例,该类另外处理请求。(它是一个可运行的类并实现了 API 的包装器)
因此,如果我在我的主类中简单地实例化 MyClass,例如 (Runnable Processor = new MyClass()),并使用它创建一个线程并运行 . 我无法访问 MyClass 或 API 类方法的方法(我对连接杀手方法特别感兴趣)。我试图像 Processor.API.eDisconnect() 一样访问它。那行不通。
但如果这样做: 创建 MyClass 的 Arraylist 然后将 MyClass 的实例添加到列表中。创建一个线程,如 Thread myThread = new Thread(List.get(0)) 。我可以访问我的 API 类方法,例如 List.get(0).API.eDisconnect()。
那么为什么第二种方法有效呢?唯一的区别是类实例是自变量还是在列表中。
是否正确练习会出现什么问题?有更好的方法吗?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package basket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
*
* @author ivan
*/
public class Basket extends JFrame implements ActionListener{
protected List<TwsHandler> TWS = new ArrayList<>();
public static void main(String[] args)
{
Basket main = new Basket();
main.Launch();
}
public void Launch()
{
TWS.add(new TwsHandler());
BorderLayout MainLayout = new BorderLayout();
JButton Start = new JButton("Start");
Start.addActionListener(this);
Start.setActionCommand("Start");
JButton Stop = new JButton("Stop");
Stop.addActionListener(this);
Stop.setActionCommand("Stop");
this.setLayout(MainLayout);
this.add(Start , BorderLayout.SOUTH);
this.add(Stop , BorderLayout.WEST);
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowClosing(WindowEvent e){System.exit(0);}
});
this.setTitle("Option basket robot");
this.setBounds(100, 100, 800, 600);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e)
{
switch (e.getActionCommand()) {
case "Start":
Thread Processor = new Thread(TWS.get(0));
Processor.start();
break;
case "Stop":
System.out.println(TWS.get(0).Eclient.isConnected());
break;
}
}
}