Reprint: Http://www.tuicool.com/articles/qE7FNv
Customizing the cell renderer in JTable is very simple and easy. For a cell renderer, its primary task is to return a Component object for the target cell to render its contents. Speaking of component, it should be enlightened, because in swing, all the graphical controls that can be displayed on the screen are component direct or indirect subclasses, that is, theoretically you can display any graphical control in a jtable cell!
Of course, there are actually some controls that cannot be displayed in a cell, such as a standalone window control such as JFrame, in order to avoid circular references and not allow the current table as a renderer, but even so, we still have a number of options available. We only need to inherit any available component subclass and implement the Tablecellrenderer interface, so we can make a cell renderer of our own. As the default cell renderer with swing, defaulttablecellrenderer is used very often, and the class inherits from JLabel, which is the simplest cell renderer implementation. Referring to this implementation, we can try to inherit from JComboBox, JButton, Jcheckbox, JProgressBar, and so on, to implement slightly more advanced UI controls such as drop-down boxes, buttons, check boxes, and progress bars in table cells.
It is worth noting that the cell UI controls do not have the ability to intercept events, that is, they simply do the data rendering work and cannot interact with the user (because the event is intercepted and processed at the top of the JTable), which also means that some of the interactive UI controls, such as dropdown boxes, checkboxes, and so on, are "only visible". However, we can solve these two problems separately by listening to jtable mouse events and switching to corresponding cells via the interface and using the cell editor.
The following code demonstrates how a custom cell renderer can be implemented to display hyperlinks in a table and automatically open the corresponding page when the link is clicked:
Package cn.ysh.studio.jtable;Import java.awt.*;Import java.awt.event.MouseEvent;Import Java.net.URL;Import Java.util.logging.Level;Import Java.util.logging.Logger;Import Javax.swing.JFrame;Import Javax.swing.JScrollPane;Import javax.swing.JTable;Import Javax.swing.event.MouseInputListener;Import Javax.swing.table.DefaultTableCellRenderer;Import Javax.swing.table.DefaultTableModel;Import Javax.swing.table.TableModel;/** * Display JTable cell renderer for hyperlinks *@author Yang Sheng Cold *@date 2013-06-20 16:08:36 * *PublicClassLinkcellrendererExtendsDefaulttablecellrendererImplementsMouseinputlistener {The row where the mouse event residesPrivateint row =-1;The column where the mouse event residesPrivateint col =-1;The currently listening tablePrivate JTable table =Null@OverridePublic Component gettablecellrenderercomponent (JTable table, Object value,Boolean isSelected,Boolean Hasfocus,int row,int column) {Restore Default statethis.table = table;Super.gettablecellrenderercomponent (table, value, isSelected, Hasfocus, Row, column);This.setforeground (Color.Black); Table.setcursor (Cursor.getpredefinedcursor (cursor.default_cursor));This.settext (Value.tostring ());If the cell that currently needs the renderer is the cell in which the mouse event residesif (row = =This.row && Column = =This.col) {If it is the second column (the second column is the column that displays the hyperlink)if (column = =1) {Change foreground (text color)This.setforeground (Color.Blue);Change the mouse shape Table.setcursor (cursor.getpredefinedcursor (cursor.hand_cursor));Show Hyperlink StylesThis.settext (""</u>Elseif (isSelected) {If the cell is selected, the foreground and background color setforeground (Table.getselectionforeground ()) are changed; SetBackground (Table.getselectionbackground ()); }else {Other cases restore the default background color setbackground (color.white); }ReturnThis }/** * Mouse Out event *@param e */Publicvoid mouseexited (MouseEvent e) {if (Table! =NULL) {int oldrow = row;int oldcol = col;After the mouse moves out of the target table, the column data is restored to the default row =-1; Col =-1;Redraw the relevant area when the previous row and column data is validif (oldrow! =-1 && oldcol! =-1) {Rectangle rect = Table.getcellrect (Oldrow, Oldcol,FALSE); Table.repaint (rect); } } }/** * Mouse Drag events *@param e */Publicvoid mousedragged (MouseEvent e) {mousemoved (e);}/** * Mouse Move Event *@param e */Publicvoid mousemoved (MouseEvent e) {if (Table! =NULL) {point P = e.getpoint ();int oldrow = row;int oldcol = col; row = Table.rowatpoint (p); col = Table.columnatpoint (p);Redraw the original areaif (oldrow! =-1 && oldcol! =-1) {Rectangle rect = Table.getcellrect (Oldrow, Oldcol,FALSE); Table.repaint (rect); }Redraw a new Areaif (Row! =-1 && col! =-1) {Rectangle rect = table.getcellrect (row, col,FALSE); Table.repaint (rect); } } }/** * Mouse Click event *@param e */Publicvoid mouseclicked (MouseEvent e) {Gets the row-and-column coordinate information for the event point P = e.getpoint ();int c = Table.columnatpoint (p);if (c! =1) {Return }int r = Table.rowatpoint (p);try {Gets the value of the target cell, which is the URL URL of the link information =The New URL (Table.getvalueat (R, c). ToString ());Open the link desktop.getdesktop (). browse (Url.touri ()) in the system's default browser; }catch (Exception ex) {Logger.getlogger (LinkCellRenderer.class.getName ()). log (Level.severe,NULL, ex); } }/** * Mouse Down event *@param e */Publicvoid mousepressed (MouseEvent e) {}/** * Mouse Release event *@param e */Publicvoid mousereleased (MouseEvent e) {}/** * Mouse Entry event *@param e */Publicvoid mouseentered (MouseEvent e) {}/** * Test Method *@param args */PublicStaticvoid Main (string[] args) {The data that will be rendered in the table object[] Header =New string[]{"Title","Link"}; object[][] data =New string[10][2];for (int i =0; I <10; i++) {data[i][0] ="Page title"; data[i][1] ="Http://www.yshjava.cn/post/529.html"; }Building a tabular data model TableModel models =New DefaultTableModel (data, header);//create Table object JTable table = new JTable (model); //create cell renderer and mouse event listener Linkcellrenderer renderer = new linkcellrenderer (); span class= "comment" >//inject renderer table.setdefaultrenderer (object.class, renderer); //inject listener table.addmouselistener (renderer); Table.addmousemotionlistener (renderer); //add love to the table scroll pane jscrollpane sp = new jscrollpane (table); //Create window program JFrame f = new JFrame ( "JTable cell hyperlink test"); F.getcontentpane (). Add (sp, borderlayout.center); F.setdefaultcloseoperation (Jframe.exit_on_close); F.setsize (800, 600); F.setlocationrelativeto (//display window f.setvisible (true);}}
As shown below:
In the example above, it only demonstrates how to influence the behavior and appearance of the corresponding cell by listening to jtable mouse events, but it does not involve how to solve the problem that the interactive UI is not available in cell jtable. To solve this problem, we need to use the Tablecelleditor cell editor to achieve, in short, the display by the renderer, interactive operation by the editor.
The principle of tablecelleditor and tablecellrenderer is almost the same, all interfaces, and Swing provides a simple default implementation that is responsible for generating UI controls to represent or edit the data of the cell. The difference is that Tablecelleditor has the ability to receive interactive events, and Tablecellrenderer does not, so you can simply think that "the editor is dynamic, responsible for editing, and the renderer is static, responsible for the presentation." The cell editor is not the subject of this article and does not explain too much. Put a window into the NetBeans Visual UI Designer, and the tables in the diagram are implemented using custom renderers and editors.
Show hyperlinks in jtable by customizing the cell renderer