提问人:Vasyl F 提问时间:4/13/2023 最后编辑:Vasyl F 更新时间:4/13/2023 访问量:34
getWidth() 在 HashMap 循环中不起作用
getWidth() is not working inside looping over HashMap
问:
朋友。 我正在尝试编写 JAVA 程序,该程序将根据用户提供的输入绘制图形。我有表示绘制名称图的画布的类。此类负责在条目列表更改或调整窗口大小时更新(重绘)图形。通过从文件中获取数据,将它们放入 ItemGraph 类中的 HashMap 中,然后遍历它以获取绘制图表所需的数据。我遇到了一个问题,我无法在 HashMap 循环中访问 getWidth() 数据,尽管相同的方法在上面的代码中为我提供了正确的信息(突出显示的粗体)。此外,当我尝试添加()一些GObjects时,它不起作用。我真的不知道那里发生了什么,问题是什么。将感谢所有的帮助。
公共类 ItemGraph 扩展了 GCanvas 实现 ItemConstants, ComponentListener {
private HashMap<String, ItemEntry> entries;
/**
* Creates a new ItemGraph object that displays the data.
*/
public ItemGraph() {
addComponentListener(this);
entries = new HashMap<>();
}
/* Method: addEntry(entry) */
/**
* Adds a new ItemEntry to the list of entries on the display.
* Note that this method does not actually draw the graph, but
* simply stores the entry; the graph is drawn by calling update.
*/
public void addEntry(ItemEntry entry) {
if (entry != null) {
entries.put(entry.getName(), entry);
}
update();
}
/**
* Updates the display image by deleting all the graphical objects
* from the canvas and then reassembling the display according to
* the list of entries. Your application must call update after
* calling either clear or addEntry; update is also called whenever
* the size of the canvas changes.
*/
public void update() {
removeAll();
double canvasHeight = getHeight();
double canvasWidth = getWidth();
double columnWidth = canvasWidth / NDECADES;
for (int i = 0; i < NDECADES; i++) {
double x = i * columnWidth;
**System.out.println(columnWidth); all working here**
GLine line = new GLine(x, 0, x, canvasHeight);
GLabel decade = new GLabel(Integer.toString(START_DECADE + i * 10),
x + GRAPH_MARGIN_SIZE / 2, canvasHeight - GRAPH_MARGIN_SIZE / 3);
add(line);
add(decade);
}
GLine topHorizontalLine = new GLine(0, GRAPH_MARGIN_SIZE, canvasWidth, GRAPH_MARGIN_SIZE);
add(topHorizontalLine);
GLine bottomHorizontalLine = new GLine(0, canvasHeight - GRAPH_MARGIN_SIZE,
canvasWidth, canvasHeight - GRAPH_MARGIN_SIZE);
add(bottomHorizontalLine);
for (ItemEntry entry : entries.values()) {
String gName = entry.getName();
**System.out.println(gName);all working here**
System.out.println(columnWidth);here i have 0**
for (int i = 0; i < NDECADES; i++) {
GOval oval = new GOval(10 * i, 10 * i, 10 * i, 10 * i);
add(oval);
}
}
}
/* Implementation of the ComponentListener interface */
public void componentHidden(ComponentEvent e) {
}
public void componentMoved(ComponentEvent e) {
}
public void componentResized(ComponentEvent e) {
update();
}
public void componentShown(ComponentEvent e) {
}
}
答: 暂无答案
评论
GCanvas
java.awt.Canvas