Java swing drawLine和drawRect没有绘制到正确的位置

问题描述 投票:1回答:1

我试图通过文件中的数据绘制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

What mine looks like

任何帮助表示赞赏,谢谢。

java swing awt java-2d
1个回答
0
投票

使用 :

convertPoint(source,x,y,destination)

它会为你做的事情。

© www.soinside.com 2019 - 2024. All rights reserved.