我正在尝试通过文件中的数据使用 javax swing 绘制网络表示。我有一个位于 (100,100) 的中央枢纽和几个我希望通过线路连接的本地枢纽。但是,本地中心放置得太远(但对于所有元素来说仍然按比例变大),并且即使一组 (x,y) 坐标设置为 (100,100),线也不会在同一位置相交。
本地集线器抽屉类:
public class hub_drawer extends JComponent{
String label;
int x;
int y;
public hub_drawer(String hub_number, int xCoord, int yCoord){
label = hub_number;
x = xCoord;
y = yCoord;
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g.create();
g2.setColor(Color.green);
g2.fillRect(x, y, 15, 15);
g2.drawLine(100, 100, x, y);
g2.setColor(Color.black);
g2.drawString(label,x+6,y-1);
}
框架类:
public class frame{
public static void main(String [] args){
JFrame f = new JFrame("Faux Broadband Network");
f.getContentPane().setBackground(Color.white);
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new central_hub());
f.setVisible(true);
try{
BufferedReader br = new BufferedReader(new FileReader("hubs.txt"));
Scanner sc = new Scanner(br);
while (sc.hasNext()){
String hubnum = sc.next();
int x = sc.nextInt();
int y = sc.nextInt();
System.out.printf("%s %d %d \n", hubnum, x, y);
f.add(new hub_drawer(hubnum, x, y));
f.setVisible(true);
}
sc.close();
br.close();
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
}
printf 函数用于确保输入正确的数据。打印函数的输出与文件数据完全相同。
What it should look like (excluding the extra lines coming from the local hubs
感谢任何帮助,谢谢。
最佳答案
用途:
convertPoint(源,x,y,目标)
它会为你做这件事。
关于Java swing drawLine 和 drawRect 未绘制在正确的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46341918/