So my program consists of two classes
1. My main class handling GUI which extends JFrame so I need to instance it to configure my JFrame .
2. MyClass which requests and processes data requested from server using an API which has to have an instance of an API class which handles requests in addition . (its a runnable class and implents a wrapper from API)
So if I simply instance MyClass like (Runnable Processor = new MyClass()), inside my main class and create a thread with it and run . I cant access methods of MyClass or API class methods (i am specifically interested in a connection killer method). Im trying to access it like Processor.API.eDisconnect(). That doesnt work.
But if do it like so : Create an Arraylist of MyClass then add an instance of MyClass to the list . Create a thread like Thread myThread = new Thread(List.get(0)) . I can access my methods of API class like List.get(0).API.eDisconnect().
So why does the second method work ? the only difference that the class instance is an independent variable or is in a list .
Is it proper practice what problems can occur ? is there a better way to do it ?
/*
* 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;
}
}
}
The only difference is that in the first case, you’re referencing a
MyClassinstance as aRunnable, whereas in the second case, you’re referencing it as aMyClass(through anArrayList, which doesn’t serve any purpose).Instead of
use
since you want to be able to call
MyClassmethods.