【发布时间】:2018-03-02 16:29:50
【问题描述】:
我正在尝试通过文件中的数据使用 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
感谢您的帮助。
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。硬编码一些数据来替换文本文件。
-
您似乎正在尝试在虚拟空间中绘制元素,但忘记了组件本身具有自己的位置(和大小)概念,因此您的绘图可能被组件的位置所抵消......猜测。我会考虑做的是使用单个组件来渲染所有集线器和线路
-
根据您的屏幕分辨率对“x 和 y”组件进行编码。您已将帧大小设为“f.setSize(500, 500);”这对于 1080p 屏幕来说太短了。随着像素的增加,基于较小分辨率构建的 UI 开始缩小。