问题
I am writing a program which :
- Creates a JPanel that contains some Shape objects which can be MouseDragged around.
- Saves an object of this class in a binary file with an ObjectOutputStream
- Retrieves the objects from the binary file (with an ObjectInputStream) and adds it in a JFrame.
My problem is that after my JPanel
is retrieved (and therefore deserialized, I take it) and added to my JFrame
, I cannot MouseDrag
my shapes anymore. No clickable actions work actually.
My teacher told me that I could fix this by using the validate() method, although I am not quite sure as to how to do it.
回答1:
The reason you don't see a change, is that the listeners of the class (even if serialized, which might be the case) do no have references to the objects they're supposed to be in contact with on the other side. Moreover, they are not being re-attached to the components that they were attached to before serialization.
As an example, the following example wouldn't work with serialization, since the listener does something to 'panel', but there's no way the listener can be "re-attached" to the button after deserialization, as well as be aware of 'who' panel is:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyPanel extends JPanel {
private JPanel innerPanel;
private JLabel label;
private JButton button;
public MyPanel() {
super(new BorderLayout(10, 10));
innerPanel = new JPanel(new BorderLayout());
innerPanel.add(label = new JLabel("PANEL"), BorderLayout.CENTER);
button = new JButton("Remove label");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.remove(label);
}
});
add(innerPanel, BorderLayout.CENTER);
add(button, BorderLayout.PAGE_END);
}
}
来源:https://stackoverflow.com/questions/22339481/how-to-make-my-mouselisteners-work-in-a-deserialized-jpanel