我需要你的帮助:) 我有一节课:
public class Main {
private static ArrayList<Integer> xCoords = new ArrayList<Integer>();
private static ArrayList<Integer> yCoords = new ArrayList<Integer>();
public static void main(String[] args) {
Adress adress2 = new Adress(6, 8);
TourManager.addAdress(adress2);
Adress adress3 = new Adress(3, 4);
TourManager.addAdress(adress3);
Adress adress4 = new Adress(9, 12);
TourManager.addAdress(adress4);
Adress adress5 = new Adress(12, 16);
TourManager.addAdress(adress5);
// Initialize intial solution
Tour currentSolution = new Tour();
currentSolution.generateIndividual();
Tour best = new Tour(currentSolution.getTour());
System.out.println("Distance From adress (0,0): " + best.getDistance());
System.out.println("Solution distance : " + best.toString()+ "\n");
// i try to sent x and y Coordinates in my too ArraList xCoords, yCoords list
// in the oder to be used in the second class to draw line.
for (int i = 0; i < best.tourSize(); i++) {
xCoords.add(i, best.getAdress(i).x);
yCoords.add(i, best.getAdress(i).y);
}
for (int i = 0; i < best.tourSize(); i++) {
System.out.print(yCoords.get(i)+ " - ");
}
new Draw(); // new instance
}
我的第二堂课是画线:
public class Draw extends JPanel {
//private static ArrayList<Integer> xCoords = new ArrayList<Integer>();
//private static ArrayList<Integer> yCoords = new ArrayList<Integer>();
// how can i recover the tow ArrayList xCoords, yCoords in the order to make a loop for to exract x,y
public void paintComponent(Graphics g)
{
final int offset = 5;
super.paintComponent(g);
g.setColor(new Color(54,34,56));
for(int i = 1; i <xCoords.size() ; i++)
{
g.fillOval(xCoords.get(i), yCoords.get(i), 8, 8);
g.setColor(Color.RED);
g.drawLine(xCoords.get(i-1)+offset, yCoords.get(i-1)+ offset, xCoords.get(i)+ offset, yCoords.get(i)+ offset);
}
}
public Draw() {
final int width = 400; // Breite des Fensters
final int height = 450; // Hoehe des Fensters
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(width, height);
f.add(this);
f.setVisible(true);
}
}
我试图在Draw类中实例化Tour,创建一个循环以在ArrayList中添加x,y坐标然后创建另一个循环以提取x,y绘制一条线但是在我的游览中我没有数据我应该重新创建地址(x,y)有数据!
答案 0 :(得分:1)
如果要将某些内容传递给另一个类,只需编写一个Class的构造函数,并为要传递的内容添加参数。
在你的情况下,它会像这样:
public class Draw extends JPanel {
...
public Draw(ArrayList<Integer> xCoords, ArrayList<Integer> yCoords) {
// your code here. You can access the arraylists by the parameter name yCoords and xCoords
}
...
}
之后,您只需创建Draw类的对象并传递数组。
希望这有帮助!