是否可以避免同一应用程序内JComponent之间在DnD中进行序列化? [英] Can serialization be avoided in DnD between JComponents within the same application?

查看:59
本文介绍了是否可以避免同一应用程序内JComponent之间在DnD中进行序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我解决了从JList到JTable对象的DnD项时遇到的神秘 IOException。显然,我传输的对象必须可序列化。



我必须注意的一件事-我要传输的类型在另一个程序包中。



p>

解决方案

您可以编写自定义TransferHandler。例如,我相信JTabel的TranferHandler将导出以逗号分隔的String,然后导入将解析该字符串以将每个令牌添加为不同的列。



所以在您的情况下,您可以以相同的方式导出数据。然后,在导入时,您将需要能够使用已解析的令牌来重新创建自定义对象。



请参阅拖放和数据传输以获取更多信息和示例。



如果DnD仅在Java应用程序之间,则可能比将实际引用传递给对象更容易。这是我尝试通过在面板之间拖动Swing组件来执行类似操作的示例:

  import java.awt。* ; 
import java.awt.datatransfer。*;
import java.awt.event。*;
import java.beans。*;
import javax.swing。*;
import javax.swing.border。*;
import javax.swing.plaf。*;
import javax.swing.text。*;
import java.io. *;

公共类DragComponent扩展了JPanel
{
//公共最终静态DataFlavor COMPONENT_FLAVOR = new DataFlavor(Component []。class, Component Array);
public static DataFlavor COMPONENT_FLAVOR;

public DragComponent()
{
try
{
COMPONENT_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType +; class = \ +组件[] .class.getName()+ \);
}
catch(异常e)
{
System.out.println(e);
}

setLayout(null);
setTransferHandler(new PanelHandler());

MouseListener侦听器=新的MouseAdapter()
{
@Override
public void mousePressed(MouseEvent e)
{
JComponent c =( JComponent)e.getSource();
TransferHandler处理程序= c.getTransferHandler();
handler.exportAsDrag(c,e,TransferHandler.MOVE);
}
};

TransferHandler处理程序= new ComponentHandler();

for(int i = 0; i< 5; i ++)
{
JLabel label = new JLabel( Label + i);
label.setSize(label.getPreferredSize());
label.setLocation(30 *(i + 1),30 *(i + 1));
label.addMouseListener(listener);
label.setTransferHandler(handler);
add(label);
}
}

私有静态无效createAndShowUI()
{
DragComponent north = new DragComponent();
north.setBackground(Color.RED);
north.setPreferredSize(new Dimension(200,200));

DragComponent south = new DragComponent();
south.setBackground(Color.YELLOW);
south.setPreferredSize(new Dimension(200,200));

JFrame frame = new JFrame( DragComponent);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(north,BorderLayout.NORTH);
frame.add(south,BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}

public static void main(String [] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

类ComponentHandler扩展TransferHandler
{
@ Override
public int getSourceActions(JComponent c)
{
返回MOVE;
}

@Override
public Transferable createTransferable(final JComponent c)
{
return new Transferable()
{
@Override
public Object getTransferData(DataFlavorflavor)
{
Component [] components = new Component [1];
components [0] = c;
个返回组件;
}

@Override
public DataFlavor [] getTransferDataFlavors()
{
DataFlavor [] flavors = new DataFlavor [1];
flavours [0] = DragComponent.COMPONENT_FLAVOR;
种回味;
}

@Override
public boolean isDataFlavorSupported(DataFlavor flavour)
{
return flavour.equals(DragComponent.COMPONENT_FLAVOR);
}
};
}

@Override
public void exportDone(JComponent c,Transferable t,int action)
{
System.out.println(c.getBounds ());
}
}

类PanelHandler扩展TransferHandler
{
@ Override
public boolean canImport(TransferSupport support)
{
if(!support.isDrop())
{
返回false;
}

布尔值canImport = support.isDataFlavorSupported(DragComponent.COMPONENT_FLAVOR);
return canImport;
}

@Override
public boolean importData(TransferSupport support)
{
if(!canImport(support))
{
返回false;
}

Component []组件;

试试
{
组件=(Component [])support.getTransferable()。getTransferData(DragComponent.COMPONENT_FLAVOR);
}
catch(异常e)
{
e.printStackTrace();
返回false;
}

组件component =组件[0];
容器容器=(容器)support.getComponent();
container.add(component);
// container.revalidate();
// container.repaint();
container.getParent()。revalidate();
container.getParent()。repaint();

JLabel标签=(JLabel)组件;
DropLocation location = support.getDropLocation();
System.out.println(label.getText()+ + + location.getDropPoint());
label.setLocation(location.getDropPoint());
返回true;
}
}


Recently I solved a "mysterious" IOException that I got while DnD items from a JList to the JTable objects. Apparently objects that I transfer must be serializable. Is this "a must", or there is a way to avoid serialization?

One thing I must note - the type I am transferring is in a different package.

解决方案

You can write a custom TransferHandler. For example I believe a TranferHandler for a JTabel will export a String that is comma delimited and then the import will parse the string to add each token as a different column.

So in your case you could export you data the same way. Then on you import you would need to be able to recreate your custom Object using the parsed tokens.

Take a look at the Swing tutorial on Drag and Drop and Data Transfer for more information and examples.

Or maybe easier if the DnD is only between your Java application than you can pass the actual reference to the object. Here is an example of my attempt to do something like this by dragging a Swing component between panels:

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.beans.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import javax.swing.text.*;
import java.io.*;

public class DragComponent extends JPanel
{
//  public final static DataFlavor COMPONENT_FLAVOR = new DataFlavor(Component[].class, "Component Array");
    public static DataFlavor COMPONENT_FLAVOR;

    public DragComponent()
    {
        try
        {
            COMPONENT_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=\"" + Component[].class.getName() + "\"");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }

        setLayout(null);
        setTransferHandler( new PanelHandler() );

        MouseListener listener = new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent e)
            {
                JComponent c = (JComponent) e.getSource();
                TransferHandler handler = c.getTransferHandler();
                handler.exportAsDrag(c, e, TransferHandler.MOVE);
            }
        };

        TransferHandler handler = new ComponentHandler();

        for (int i = 0; i < 5; i++)
        {
            JLabel label = new JLabel("Label " + i);
            label.setSize( label.getPreferredSize() );
            label.setLocation(30 * (i+1), 30 * (i+1));
            label.addMouseListener( listener );
            label.setTransferHandler( handler );
            add( label );
        }
    }

    private static void createAndShowUI()
    {
        DragComponent north = new DragComponent();
        north.setBackground(Color.RED);
        north.setPreferredSize( new Dimension(200, 200) );

        DragComponent south = new DragComponent();
        south.setBackground(Color.YELLOW);
        south.setPreferredSize( new Dimension(200, 200) );

        JFrame frame = new JFrame("DragComponent");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(north, BorderLayout.NORTH);
        frame.add(south, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

class ComponentHandler extends TransferHandler
{
    @Override
    public int getSourceActions(JComponent c)
    {
        return MOVE;
    }

    @Override
    public Transferable createTransferable(final JComponent c)
    {
        return new Transferable()
        {
            @Override
            public Object getTransferData(DataFlavor flavor)
            {
                Component[] components = new Component[1];
                components[0] = c;
                return components;
            }

            @Override
            public DataFlavor[] getTransferDataFlavors()
            {
                DataFlavor[] flavors = new DataFlavor[1];
                flavors[0] = DragComponent.COMPONENT_FLAVOR;
                return flavors;
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor flavor)
            {
                return flavor.equals(DragComponent.COMPONENT_FLAVOR);
            }
        };
    }

    @Override
    public void exportDone(JComponent c, Transferable t, int action)
    {
        System.out.println(c.getBounds());
    }
}

class PanelHandler extends TransferHandler
{
    @Override
    public boolean canImport(TransferSupport support)
    {
        if (!support.isDrop())
        {
            return false;
        }

        boolean canImport = support.isDataFlavorSupported(DragComponent.COMPONENT_FLAVOR);
        return canImport;
    }

    @Override
    public boolean importData(TransferSupport support)
    {
        if (!canImport(support))
        {
            return false;
        }

        Component[] components;

        try
        {
            components = (Component[])support.getTransferable().getTransferData(DragComponent.COMPONENT_FLAVOR);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }

        Component component = components[0];
        Container container = (Container)support.getComponent();
        container.add(component);
//      container.revalidate();
//      container.repaint();
        container.getParent().revalidate();
        container.getParent().repaint();

        JLabel label = (JLabel)component;
        DropLocation location = support.getDropLocation();
        System.out.println(label.getText() + " + " + location.getDropPoint());
        label.setLocation( location.getDropPoint() );
        return true;
    }
}

这篇关于是否可以避免同一应用程序内JComponent之间在DnD中进行序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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