如何使我的MouseListener在反序列化的JPanel中工作? [英] How to make my MouseListeners work in a deserialized JPanel?

查看:148
本文介绍了如何使我的MouseListener在反序列化的JPanel中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,

  1. 创建一个 JPanel 包含一些Shape对象,这些对象可以是 ObjectInputStream )并将其添加到 JFrame .

我的问题是,在检索到我的JPanel(并因此对其进行反序列化)并将其添加到我的JFrame之后,我无法再MouseDrag我的形状了.实际没有可点击的动作.

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.

推荐答案

您看不到更改的原因是该类的侦听器(即使是序列化的,也可能是序列化的)没有对他们应该在另一侧接触的对象.而且,它们不会在序列化之前重新附加到它们所附加的组件上.

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);
    }
}

这篇关于如何使我的MouseListener在反序列化的JPanel中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆