Realize copy and paste features between Swing JTables and Excel

zhaozj2021-02-08  356

Many business applications today are developed using Java, and this application developed with Java will be more. Swing JTAble components in many applications are used to display data in a similar spreadsheet. If the business application can import data into Microsoft Excel and export data from Microsoft Excel, it will make it easy for users to use the powerful features of the unnecessary spreadsheet program. This Java tip will help you understand the system clipboard and make your JTable to interact with Excel and interoperability. You will see that this useful function is added to achieve this useful function by adding another one-line code in the current application.

To achieve this goal, just copy the file ExceLadapter.java given here, and make sure your application can find an ExceLadapter.class file; after finishing, JTable can talk to Excel. ! We will show you only through this line of code, how to achieve the copy and paste (Ctrl V) and paste (Ctrl V) and paste (Ctrl V) and paste (Ctrl V). An example application using ExceLadapter is also provided.

The code below is the adapter code that actually completes this task (called ExceLadapter.java): import java.Awt. *;

Import java.awt.event. *;

Import javax.swing. *;

Import java.awt.datatransfer. *;

Import java.util. *;

/ **

* ExceLadapter implements copy paste in jtables

* Clipboard function. Clipboard data format used by the adapter

* Compatible with the clipboard format used in Excel. This provides

* Supported interoperabilities between JTables and Excel.

* /

Public Class ExceLadapter Implements ActionListener

{

Private string rower, value;

Private clipboard system;

PRIVATE STRINGSELECTION STSEL;

Private jtable jtable1;

/ **

* The Excel adapter consists of JTable,

* It implements copy paste on JTABLE

* Function and act as a clipboard monitor program.

* /

Public ExceLadapter (jtable myjtable)

{

Jtable1 = myjtable;

KeyStroke Copy = Keystroke.getKeystroke (KeyEvent.vk_c, ActionEvent.ctrl_mask, false);

/ / Determine the copy button user can modify it

// To implement a replication function of other buttons.

Keystroke Paste = keyStroke.getKeystroke (KeyEvent.vk_v, ActionEvent.ctrl_mask, false);

/ / Determine the paste button user can modify it

// To implement a replication function of other buttons.

JTable1.registerKeyboardAction (this, "copy", copy, jcomponent.when_focused);

JTable1.registerKeyboardAction (this, "paste", paste, jcomponent.when_focused);

System = Toolkit.getDefaultToolkit (). getsystemclipboard ();

}

/ **

* This adapter runs a common reading method for the chart.

* /

Public JTable getJtable () {returni jtable1;}

Public void setjtable (jtable jtable1) {this.jtable1 = jtable1;}

/ **

* Activate this method on the buttons we listen to this implementation.

* Here, it listens to replication and paste ActionCommands.

* Contains selection of non-adjacent cells, resulting in invalidation,

* And then copy the actions cannot be performed.

* Paste method is to put the upper left corner of the selected content

* The first element of the currently selected content of JTABLE is aligned.

* /

Public Void ActionPerformed (ActionEvent E)

{

IF (E.GetActionCommand (). Compareto ("copy") == 0)

{

StringBuffer SBF = new stringbuffer ();

// Check to make sure we only choose a cell

// adjacent

INT Numcols = jtable1.getSelectedColumnCount ();

Int nuMrows = jtable1.getSelectedRowCount ();

int [] rowsselected = jtable1.getSelectedROWS ();

int [] colsselected = jtable1.getSelected gTSELECTEDCOLUMNS ();

IF (! (nuMrows-1 == ROWSSELECTED [ROWSSELECTED.LENGTH-1] -RowSelected [0] &&

Numrows == ROWSSELECTED.LENGTH) &&

(Numcols-1 == colsselected [colortated.length-1] -colsselected [0] &&

Numcols == calsselected.length))))))))))))

{

JOPTIONPANE.SHOWMESSAGEDIALOG (NULL, "Invalid Copy Selection",

"Invalid Copy Selection",

JOPTIONPANE.ERROR_MESSAGE);

Return;

}

For (int i = 0; i

{

For (int J = 0; J

{

SBF.Append (jtable1.getvalueat (rowsselected [i], colsselected [j]));

IF (j

}

SBF.Append ("/ n");

}

Stsel = new stringselection (sbf.tostring ());

System = Toolkit.getDefaultToolkit (). getsystemclipboard ();

System.SetContents (Stsel, Stsel);

}

IF (E.GetActionCommand (). Compareto ("Paste") == 0)

{

System.out.Println ("Trying to Paste");

INT Startrow = (jtable1.getSelectedRows ()) [0];

INT StartCol = (JTable1.GetSelectedColumns ()) [0];

Try

{

String Trstring = (String) (THISTRINTENTS (THIS) .GetTransferData (DataFlavor.StringFlavor); System.out.Println ("String is:" TRSTRING);

StringTokenizer ST1 = New StringTokenizer (Trstring, "/ N");

For (int i = 0; st1.hasmoretoKens (); i )

{

Rowstring = st1.nextToken ();

StringTokenizer ST2 = New StringTokenizer (Rowstring, "/ T");

For (int J = 0; st2.hasmoretoKens (); J )

{

Value = (string) st2.nextToken ();

IF (StarTrow i

Startcol J

JTable1.SetValueat (Value, Startrow i, StartCol J);

System.out.println ("Putting" Value "AT

Row = " Startrow i " Column = " StartCol J);

}

}

}

Catch (Exception EX) {EX.PrintStackTrace ();

}

}

}

The Sample Application Below is a sample application frame1.java, which uses ExceLadapter to implement JTABLE compatibility with Excel. Import java.awt. *;

Import javax.swing. *;

Public Class Frame1 Extends Frame

{

BorderLayout BorderLayout1 = New BorderLayout ();

JTable JTable1;

Object [] [] data = new object [4] [4];

Object header [] = {"Jan", "Feb", "Mar", "APR"};

Public static void main (string args [])

{

Frame1 myframe = new frame1 ();

MyFrame.setsize (New Dimension (250, 250));

myframe.setvisible (TRUE);

}

Public frame1 ()

{

Super ();

Try

{

Jbinit ();

}

Catch (Exception E)

{

E.PrintStackTrace ();

}

}

Private void jbinit () THROWS EXCEPTION

{

For (int i = 0; i <4; i )

For (int J = 0; j <4; j )

Data [i] [j] = new integer (i * 10 j);

System.out.println ("Header Length =" Header [1]);

JTable1 = New JTABLE (DATA, HEADER);

JTable1.setCellSelectionNabled (TRUE);

"Excel Lent JTable"); jtable1.setBackground; Color.pink

This.setLayout (borderlayout1);

THIS.SETSIZE (New Dimension (400, 300));

This.SetBackground (Color.White);

This.Add (jtable1, borderlayout.center);

// This is the line of adding replication and paste!

ExceLadapter myad = new exceladapter (jtable1);

}

}

The clipboard format of Excel is very simple in the clipboard format of Excel. It uses a tab to divide the elements on one line and take a line with a wrap. Thus, when you copy a set of continuous and / or adjacent cells, Excel only marks the spreadsheet data into a long string, and each cell value is separated by tabs in the string. . What should I do if the selected cell is not adjacent? Very simple: Excel does not let you copy the selected content to the clipboard. This behavior is imitated by the adapter described herein. If the selected cell is not adjacent, you will not copy data. In Excel, a dialog will pop up to tell us that it is not allowed to copy; this behavior is again imitated by the adapter.

Code Simple Interpretation To use this feature, you need to download the ExceLadapter.java file, compile them, add the last line in the sample application to a location in your code to activate the adapter on the JTABLE. In the adapter, the activation button of the replication and paste function has been registered. Thereafter, the ActionPerformed method will be called whenever you typing the activated button. If it is a copy operation, the selected cell data will be appropriately tagged for Excel, and is written to the system clipboard. If it is a paste operation, the data in the system clipboard is converted into a string form, and after analysis, implant in the JTABLES cell according to the selected cell.

Conclusion Users who use Java-written tables often want data in JTables to be similar to the data processing method in Excel. It is not written code to implement replication-paste functions on each JTABLE, but more simply writes a common adapter, just add a line of code to each JTABLE. The adapters provided in this Java TIP do this.

转载请注明原文地址:https://www.9cbs.com/read-823.html

New Post(0)