我正在制作一个程序,涉及在屏幕上点击并拖动JLabel,这些屏幕上有连接它们的线条。一切正常。但是当我使用序列化添加保存/加载功能时,发生了奇怪的事情。现在当我加载文件时,它看起来就像我保存它时一样,但是如果我尝试拖动组件,附加的线不会保持笔直 - 它会被拖动JLabel的位置跟踪,并删除如果你把它拖回来。
这是我的“连接”的类(“输入”和“输出”是位于该行的端点的对象):
class Connection extends JComponent {
//Connections connect components together
Output output;
Input input;
int id;
public Connection(int ID, Output output, Input input) {
id = ID;
currentConnectionID++;
allConnections.put(id, this);
this.output = output;
this.input = input;
//if (output.isAvailable()) output.connections.add(this);
//if (input.isAvailable()) input.connections.add(this);
}
public void paintConnection(Graphics2D g2d) {
//super.paintComponent(g2d);
Line2D.Double line = new Line2D.Double(output.getX(), output.getY(), input.getX(), input.getY());
g2d.draw(line);
//g2d.drawLine(output.getX(), output.getY(), input.getX(), input.getY());
output.inputsReceivingThis.add(input); //Now the output "knows" where it's going
if (mode.equals("choosingInput")) {
input.component.numberConnected +=1;
}
}
}
这是我的保存和加载功能:
void save() throws IOException {
String savepoint = "C:\\docs\\hi.txt";
FileOutputStream fileOut = new FileOutputStream(savepoint);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.println(lines.size());
for (Component c : components) {
for (Output o : c.outputs) {
for (Input i : o.inputsReceivingThis) {
System.out.println(i.component.type);
}
}
}
ProjectState state = new ProjectState();
out.writeObject(state);
out.close();
fileOut.close();
}
void load() throws IOException, ClassNotFoundException {
ProjectState state;
String loadpoint = "C:\\docs\\hi.txt";
FileInputStream fileIn = new FileInputStream(loadpoint);
ObjectInputStream in = new ObjectInputStream(fileIn);
state = (ProjectState) in.readObject();
in.close();
fileIn.close();
drawPanel.removeAll();
components.clear();
lines.clear();
components=state.projectComponents;
for (Component component : state.projectComponents) {
drawPanel.add(component);
for (Output output : component.outputs) {
for (Input input : output.inputsReceivingThis) {
Connection c = new Connection(currentConnectionID, output, input);
lines.add(c);
}
}
}
drawPanel.repaint();
}
编辑:对不起,我的问题不是很清楚...我想知道的是,为什么从保存文件加载然后拖动时,线条被绘制得不直,我怎么能直线?我想我也应该包含点击并拖动代码:
abstract class Component extends JLabel implements MouseListener, MouseMotionListener, Serializable {
public void mousePressed(MouseEvent e) { //the "click" of click-and-drag
startDragX = e.getX();
startDragY = e.getY();
}
public void mouseDragged(MouseEvent e) {
int newX = getX() + (e.getX() - startDragX);
int newY = getY() + (e.getY() - startDragY);
setLocation(newX, newY);
inDrag = true;
frame.repaint();
}
}