gpt4 book ai didi

java - 将 main 方法中创建的 arrayList 传递给另一个类

转载 作者:行者123 更新时间:2023-12-01 10:18:58 25 4
gpt4 key购买 nike

我需要你的帮助:)我有一个主要类(class):

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 来绘制一条线,但在我的旅程中我没有数据,我应该重新创建 Adress (x, y) 获得数据!

最佳答案

如果您想将某些内容传递给另一个类,只需编写该类的构造函数并为您要传递的内容添加参数即可。

在你的情况下,它会是这样的:

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 类的对象并传递数组。

希望这有帮助!

关于java - 将 main 方法中创建的 arrayList 传递给另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35744436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com