[英]Plotting points in java
嘿,我应该输入一个城市列表以及x和y坐标并将其绘制出来。 我将所有城市作为具有x和y坐标的顶点。 现在,我正在尝试绘制它们,但似乎看不到自己在做错什么,也没有收到错误。 这是我第一次使用GUI,因此可能是一个愚蠢的错误。
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.Arrays;
public class GraphMaker{
public GraphMaker(Vertex[] a )
{
JFrame frame = new JFrame();
String start = "Start";
int columns=20;
String end = "End";
JTextField startCity = new JTextField(start,columns);
JTextField endCity = new JTextField(end,columns);
JButton button = new JButton("Find Path");
//button.addActionListener(button);
int length = a.length;
Vertex current = a[0];
CityComponent cityPanel = new CityComponent(current);
/*for(int i=0; i < length; i++){
Vertex current = a[i];
g2.draw(new Line2D.Double(x,y,x,y));
}*/
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(startCity);
panel.add(endCity);
panel.add(button);
frame.setLayout(new BorderLayout());
frame.add(cityPanel,BorderLayout.CENTER);
frame.add(panel,BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
return;
}
}
import javax.swing.*;
import java.awt.*;
public class CityComponent extends JComponent {
private Vertex m;
private int x = 0;
private int y = 0;
public CityComponent(Vertex m) {
this.m = m;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
m.draw(g2);
}
}
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
public class Vertex{
public String element;
public Double x;
public Double y;
public Vertex(String city, String a, String b){
this.element = city;
this.x = Double.parseDouble(a);
this.y = Double.parseDouble(b);
}
public void draw(Graphics2D g2){
Point2D.Double r1 = new Point2D.Double(x/10, y/10);
Line2D.Double line = new Line2D.Double(r1,r1);
g2.draw(line);
}
}
您正在尝试使用一个不存在的Graphics对象。 正如我所看到的,您可以在此处进行以下两种选择之一:
paintComponent(Graphics g)
方法,使用for循环遍历顶点,并使用JVM提供的Graphics对象进行绘制... getGraphics()
获得的Graphics对象来绘制BufferedImage。 然后可以将图像放入ImageIcon,然后将图标放入JLabel。 getGraphics()
获得的Graphics对象。 您已被警告。 编辑
我现在看到的是扩展JComponent的CityComponent类,现在应该使用此类进行绘制。 关键是将正确的顶点传递到其中,这是我不知道您是否做得正确的事情,因为我们看不到如何构造GraphMaker类。
您可能希望告诉我们您的代码是什么,是给您的,还给我们您的确切要求。 您的某些代码似乎仍然有些偏离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.