>我需要制作GUI应用程序,该应用程序从用户选择的文件中获取坐标,并使用.drawLine与它们一起划线。我试图将这些点保存到 ArrayList,然后初始化它们,但我不知道如何继续并使其正常工作。请帮助我。
该文件看起来像这样,可以采用任何类型。
- 2,4,3,8 (x1, y1, x2, y2(
- 8,0,7,20
- 0,0,800,962
这是最有效的代码。
public class Line extends JPanel {
ArrayList<Integer> points = new ArrayList<>();
public Line() {
points.add(20);
points.add(40);
points.add(250);
points.add(40);
}
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < points.size(); i++) {
g2d.drawLine(points.get(i), points.get(i), points.get(i), points.get(i));
System.out.println(points.get(i));
}
}
}
因此,首先读取文件,然后添加到列表中。
此外,它只是绘制循环的点的cos。当它循环时,如果第一个数字是 8,你的循环绘制的是g2d.drawLine(8,8,8,8);
这是我的代码片段。未测试,但应该工作正常:
ArrayList<Integer> points = new ArrayList<>();
public Line(String filePath) {
points = readFile(filePath);
}
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if(points!= null && points.size()>=4) {
g2d.drawLine(points.get(0), points.get(1), points.get(2), points.get(3));
}
}
public ArrayList<Integer> readFile(String filePath){
BufferedReader br = null;
FileReader fr = null;
ArrayList<Integer> list = new ArrayList();
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(filePath);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
String[] splitted = sCurrentLine.split(",");
for (int i = 0; i < splitted.length; i++) {
try {
list.add(Integer.parseInt(splitted[i].trim()));
}
catch (Exception ex){
System.out.println(splitted[i] + " is not a valid number/integer");
}
}
}
System.out.println(list);
}
catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return list;
}
下面是如何读取文件并存储线条信息,然后绘制它们的示例。
为了方便起见,它使用Graphics2D
的draw(Shape(方法,因此您可以在读取文件时直接存储Shape
对象。
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Line extends JPanel {
ArrayList<Shape> lines = new ArrayList<>();
public Line() {
try (Scanner scanner = new Scanner(new File("path_to_your_file"))) {
while (scanner.hasNextLine()) {
// split the line on the comma separator
String[] parts = scanner.nextLine().trim().split("\,");
// read the coordinates
int x1 = Integer.valueOf(parts[0]);
int y1 = Integer.valueOf(parts[1]);
int x2 = Integer.valueOf(parts[2]);
int y2 = Integer.valueOf(parts[3]);
// create a Line and store it
lines.add(new Line2D.Float(x1, y1, x2, y2));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void paintComponent(final Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// draw all the lines
for (Shape line : lines) {
g2d.draw(line);
}
}
}