程序简介
大家好。今天早上我很无聊,决定写一个绘图程序。最终我将能够在此软件上运行诸如 Dijksta 算法 之类的东西。
当屏幕上发生任何变化时,将调用 JPanel
的 repaint
方法,所有内容都会被绘制到该方法。这是 JPanel
绘制方法:
public void paint(Graphics g)
{
for(Node node : graph.getNodes()){
node.paint(g);
}
for(Link link : graph.getLinks()){
link.paint(g);
}
}
它只是循环遍历列表中的每个元素,并绘制它们。
节点类的绘制方法是:
public void paint(Graphics g)
{
g.setColor(color);
g.drawOval(location.x, location.y, 50, 50);
g.setColor(Color.BLACK);
g.drawString(name, location.x + 20, location.y + 20);
}
链接是:
public void paint(Graphics g)
{
Point p1 = node1.getLocation();
Point p2 = node2.getLocation();
// Grab the two nodes from the link.
g.drawLine(p1.x + 20, p1.y + 20, p2.x + 20, p2.y + 20);
// Draw the line between them.
int midPointX = ((p1.x + p2.x) / 2) + (100 / (p2.x - p1.x));
int midPointY = ((p1.y + p2.y) / 2) + 30;
// Compute the mid point of the line and get it closer to the line.
g.setColor(Color.BLACK);
g.drawString(String.valueOf(weight), midPointX, midPointY);
}
问题
我遇到的问题是在使用 JOptionPane
类时出现的。当我选择添加新节点的选项并选择放置它的位置时,会弹出一个 inputDialog
,询问节点的名称。
节点添加正常,因为出现这种情况:
这是个常见的问题吗;可能是 paint
或 repaint
的问题?
不过,这里是调用 inputDialog
的代码:
Function addNode = functionFac.getInstance(state);
String name = "";
while(!name.matches("[A-Za-z]+")) {
name = JOptionPane.showInputDialog("Please enter the name of the node.", null);
}
addNode.execute(stage, new NodeMessage(arg0.getPoint(), name));
PS:Function是我写的接口(interface)类型。
最佳答案
“Swing 程序应该覆盖 paintComponent()
而不是覆盖 paint()
。”— Painting in AWT and Swing: The Paint Methods .
“如果您不尊重不透明属性,您可能会看到视觉伪像。”— JComponent
另见 Q&A检查相关问题。
关于java - 奇怪的重绘功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15954361/