在两个不同的内部框架java中的两个表之间拖放

时间:2014-04-24 11:11:26

标签: java swing drag-and-drop jtable jinternalframe

我有一个应用程序,其中两个不同的InternalFrame中有两个Jtables,一个确实有一个带有列的模型,另一个没有,并且想法是将一些列从一个拖到另一个出于打印目的..因为在我正在做的这个应用程序中,所有列都很重要但不是所有列都必须是可打印的,我们只需要打印一些列。

所以我的问题是:是否可以在两个不同内部框架的两个jtables之间拖放列来创建要打印的模型。如果它是如何做到的?

提前致谢。

在尝试了@Kleopatra的解决方案之后,我仍然无法删除列,至少现在我可以拖动它们了:p!

首先,当我运行程序时,问题是JavaNullPointerExeption,它是关于获取源表模型的东西; “JXTable target = new JXTable(source.getModel())”,然后我为这两个表创建了两个模型(具有相同的结构),但现在的问题是,当我尝试删除它时,有“停止”标志;你知道中有一条对角线的圆圈。 我尝试了一切来解决这个问题,但是徒劳......所以我很感激你的帮助。

这是源表的代码:

package presentation;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.EventQueue;

import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.JXTable;
import domain.Bulletin_Assurance;

public class Presentation_Bulletin_assur extends JInternalFrame {

/**
 * 
 */
private static final long serialVersionUID = 1L;



/**
 * Launch the application.
 */



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

                final Presentation_Bulletin_assur frame = new Presentation_Bulletin_assur();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */




TransferHandler handler;
final static String[] columnNames = { "Num du bulletin", "Num d'adhésion", "Pièce", "Nom du Beneficiaire", "Nom du malade", "Nom Medecin", "Date de consultation","Frais Medecin", "Honoraire", "Pharmacie", "Injection", "Laboratoire", "Radio", "Monture", "Verre", "Soins", "Prothése", "Hospitalisation", "Divers 1", "Divers 2", "Divers 3" };





final static Object[][] data = {
    {new Integer(Bulletin_Assurance.getNum_bulletin()),
    new Long (Bulletin_Assurance.getNum_adhesion()), 
    new Long(Bulletin_Assurance.getPiece()), 
    Bulletin_Assurance.getNom_Beneficiaire(),
    Bulletin_Assurance.getNom_du_malade(),
    Bulletin_Assurance.getNom_Medecin(),
    Bulletin_Assurance.getDate_Consultation(),
     new Double(Bulletin_Assurance.getMedecin()),
     new Float(Bulletin_Assurance.getHonor()),
     new Float(Bulletin_Assurance.getPharmacie()),
     new Float(Bulletin_Assurance.getInjection()),
     new Float(Bulletin_Assurance.getLaboratoire()),
     new Float(Bulletin_Assurance.getRadio()),
     new Float(Bulletin_Assurance.getMonture()),
     new Float(Bulletin_Assurance.getVerre()),
     new Float(Bulletin_Assurance.getSoins()),
     new Float(Bulletin_Assurance.getProthese()),
     new Float(Bulletin_Assurance.getHospitalisation()),
     new Float(Bulletin_Assurance.getDiver_1()),
     new Float(Bulletin_Assurance.getDiver_2()),
     },
     };

static DefaultTableModel model=new DefaultTableModel(data, columnNames);;
public static JXTable table=new JXTable(model);







public Presentation_Bulletin_assur() {
    setFrameIcon(null);
    setBounds(100, 100, 511, 492);
    setResizable(true);
    setLayout(new FlowLayout());
        handler = new DragDropConfig();
    table.setTransferHandler(handler);
    table.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    table.setRowSelectionAllowed(true);
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    table.setSurrendersFocusOnKeystroke(true);
    table.setFont(new Font("Times New Roman", Font.PLAIN, 13));
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.setDragEnabled(true);

    getContentPane().setLayout(new BorderLayout());
    setClosable(true);

    final JScrollPane scrollPane = new JScrollPane(table);
    table.setFillsViewportHeight(true);
    scrollPane.getViewport();
    getContentPane().add(scrollPane);
}

这是目标表的代码:

package presentation;
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.table.TableColumnExt;
public class Imprimer_bordereau extends JInternalFrame implements ActionListener {

/**
 * 
 */
private static final long serialVersionUID = 1L;
private JScrollPane sc;
static JXTable bordereau;
private JButton imprimer;

Presentation_Bulletin_assur pr;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Imprimer_bordereau frame = new Imprimer_bordereau();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Imprimer_bordereau() {
    setBounds(100, 100, 450, 300);
    setResizable(true);



    DefaultTableModel model=(DefaultTableModel) Presentation_Bulletin_assur.table.getModel();

    bordereau=new JXTable(model);
    bordereau.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    bordereau.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    bordereau.setRowSelectionAllowed(true);
    bordereau.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    bordereau.setSurrendersFocusOnKeystroke(true);
    bordereau.setFont(new Font("Times New Roman", Font.PLAIN, 13));
    bordereau.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    sc= new JScrollPane(bordereau);
    bordereau.setFillsViewportHeight(true);
    sc.getViewport();
    getContentPane().add(sc, BorderLayout.CENTER);



    List<TableColumn> columns = bordereau.getColumns();
    for (TableColumn tableColumn : columns) 
    {
        ((TableColumnExt) tableColumn).setVisible(false);
    }

    TransferHandler handler=new DragDropConfig();
    bordereau.setTransferHandler(handler);
    bordereau.setDragEnabled(true);




    imprimer= new JButton("Imprimer");
    imprimer.setFont(new Font("Times New Roman", Font.PLAIN, 14));
    imprimer.addActionListener(this);
    getContentPane().add(imprimer, BorderLayout.SOUTH);

}

public void actionPerformed(ActionEvent arg0) 
{
    if(arg0.getSource()==imprimer)
    {
        pr=new Presentation_Bulletin_assur();
        pr.setTitle("Les informations à imprimer");
        Presentation_Bulletin_assur.table.setToolTipText("Pour choisir les informations à imprimer, \n il suffit de maintenir le clic de souris sur une case, \nd e les faire glisser vers la fenêtre intitulée fenêtre d'impression,\n et de les déposer");
        MainPage.dp.add(pr);
        pr.setVisible(true);
    }


}
}

最后,转移处理程序:

package presentation;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.util.List;
import javax.activation.ActivationDataFlavor;
import javax.activation.DataHandler;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import javax.swing.table.TableColumn;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.table.TableColumnExt;


public class DragDropConfig extends TransferHandler {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private final DataFlavor localObjectFlavor = new ActivationDataFlavor(
        Integer.class, DataFlavor.javaJVMLocalObjectMimeType,
        "Integer Column Model Index");



protected Transferable createTransferable(JComponent c) {
    JXTable table = (JXTable) c;
    int index = table.getSelectedColumn();
    TableColumnExt column = table.getColumnExt(index);
    return new DataHandler(column.getModelIndex(),
            localObjectFlavor.getMimeType());
}


public boolean canImport(TransferHandler.TransferSupport info) {
    return info.isDataFlavorSupported(localObjectFlavor);
}


public int getSourceActions(JComponent c) {
    return TransferHandler.COPY;
}


public boolean importData(TransferHandler.TransferSupport info) {
    JXTable bordereau = (JXTable) info.getComponent();
    JXTable.DropLocation dl = (JXTable.DropLocation) info.getDropLocation();
    try {
        Integer columnFrom = (Integer) info.getTransferable().getTransferData(
                localObjectFlavor);
        TableColumnExt tableColumn = null;
        List<TableColumn> columns = bordereau.getColumns(true);
        for (TableColumn column : columns) {
            if (column.getModelIndex() == columnFrom) {
                ((TableColumnExt) column).setVisible(true);
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
}

顺便说一下,在transferhandler中,第48行中的droplocation“dl”和第52行中的“tableColumn”被标记为未使用的变量。 (也许它与此有关,对不起我的无知:p)

1 个答案:

答案 0 :(得分:2)

最简单(假设您使用内置支持进行打印,即打印表格的可见部分)将是

  • 在两个表格上使用相同的模型
  • 启动不带任何列的可打印表(或将其visible属性设置为false)
  • on drop,添加一个对应传输列(model!)列索引的列(或将其可见性设置为true)

下面是一个使用SwingX的(非常快速)示例,特别是它对列可见性和激活框架的支持

// a TransferHandler for dragging a column between tables
// by changing its visiblity property
public class TableColumnTransferHandler extends TransferHandler {
    private final DataFlavor localObjectFlavor = new ActivationDataFlavor(
            Integer.class, DataFlavor.javaJVMLocalObjectMimeType,
            "Integer Column Model Index");


    @Override
    protected Transferable createTransferable(JComponent c) {
        JXTable table = (JXTable) c;
        int index = table.getSelectedColumn();
        TableColumnExt column = table.getColumnExt(index);
        return new DataHandler(column.getModelIndex(),
                localObjectFlavor.getMimeType());
    }

    @Override
    public boolean canImport(TransferHandler.TransferSupport info) {
        return info.isDataFlavorSupported(localObjectFlavor);
    }

    @Override
    public int getSourceActions(JComponent c) {
        return TransferHandler.MOVE;
    }

    @Override
    public boolean importData(TransferHandler.TransferSupport info) {
        JXTable target = (JXTable) info.getComponent();
        JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
        try {
            Integer columnFrom = (Integer) info.getTransferable().getTransferData(
                    localObjectFlavor);
            TableColumnExt tableColumn = null;
            List<TableColumn> columns = target.getColumns(true);
            for (TableColumn column : columns) {
                if (column.getModelIndex() == columnFrom) {
                    ((TableColumnExt) column).setVisible(true);
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}

// its usage
JXTable source = new JXTable(new AncientSwingTeam());
JXTable printable = new JXTable(source.getModel());
TransferHandler handler = new TableColumnTransferHandler();
List<TableColumn> columns = printable.getColumns();
for (TableColumn tableColumn : columns) {
    ((TableColumnExt) tableColumn).setVisible(false);
}
source.setTransferHandler(handler);
source.setDragEnabled(true);
printable.setTransferHandler(handler);
printable.setDragEnabled(true);