[英]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.