Usage example of JTable renderer and editor in Java Swing

This article describes the usage of JTable renderer and editor in Java swing. Share with you for your reference, as follows:

The content, appearance and event response of JTable are largely controlled by the renderer and editor. Specifically, the renderer is responsible for the appearance of cells, such as foreground color, background color, and cell tips; The editor is responsible for cell content and event response. By default, the editor is in the form of text box. You can also use drop-down menus, buttons, radio buttons, etc. Here is a demo program to illustrate the basic usage of renderer and editor.

JButtonTableExample. java

The above is the main program, which constructs GUI, table and model. And set up the renderer and editor of table.

ButtonRenderer. java

The customized renderer must implement tablecellrenderer and gettablecellrendercomponent methods. In this method, you can specify the text, cell tips, colors, fonts, and so on for the renderer. Note that the text here is only the displayed content, not the actual data of the cell.

ButtonEditor. java

This editor implements a button, and the corresponding business codes are located in its event response function. The custom renderer must inherit defaultcelleditor and overload its gettablecelleditorcomponent method. The parameters of gettablecelleditorcomponent provide the table object, cell value, cell selection flag and cell coordinates, and return the JComponent component of the renderer representing the cell. In this method, we save the cell value as the member variable cellvalue and return a button. The getcelleditorvalue method is used to return the cell value, which needs to be specified explicitly. In the event response function of the button, this demo outputs the corresponding cell values through the pop-up dialog box. Then, the fireEditingStopped method is invoked to refresh the renderer. Note that this step is not necessary, because the business code in the renderer is likely to change the cell value, resulting in the need for the renderer to refresh.

The operation effect is as follows:

The effect of clicking button1 is as follows:

More readers interested in Java related content can view the special topics of this site: Java data structure and algorithm tutorial, summary of Java character and string operation skills, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>