Tables (3)

Source: Internet
Author: User
18.5 jtableheader class

Each jtableheader instance represents one of the headers of all different columns. The jtableheader object set is placed in the column header view in jscrollpane.

We seldom need to use jtableheader directly. However, we can configure some features of the column header.

18.5.1 create jtableheader

Jtableheader has two attributes. One uses the default tablecolumnmodel, And the other needs to explicitly specify the model.

public JTableHeader()JComponent headerComponent = new JTableHeader()public JTableHeader(TableColumnModel columnModel)JComponent headerComponent = new JTableHeader(aColumnModel)

18.5.2 jtableheader attributes

As shown in Table 18-11, jtableheader has ten different attributes. These attributes allow you to configure what the user can do through a specific column header or how the column header is displayed.

18.5.3 use the tooltip In the table Header

By default, if we set a tooltip for the table header, all column headers share the same tooltip text. To specify the tooltip text for a specific column, we need to create or retrieve the Renderer, and then set the tooltip for the Renderer. This is also true for a single unit. Figure 18-12 shows the custom result.

The custom source code in Figure 18-12 is displayed in list 18-13. Unless we have set the column header before, it is not necessary to first check that the header of a specific column is null.

JLabel headerRenderer = new DefaultTableCellRenderer();String columnName = table.getModel().getColumnName(0);headerRenderer.setText(columnName);headerRenderer.setToolTipText("Wave");TableColumnModel columnModel = table.getColumnModel();TableColumn englishColumn = columnModel.getColumn(0);englishColumn.setHeaderRenderer((TableCellRenderer)headerRenderer);

18.5.4 custom jtableheader View

The available set of jtableheaderuiresource attributes is displayed in table 18-12. These five attributes control the color, Font, and border of the header Renderer.

18.6 edit a table Unit

The jtable unit editing is basically the same as the jtree unit editing. In fact, the default table Unit Editor, defaultcelleditor, implements the tablecelleditor and treecelleditor interfaces, so that we can use the same editor for the table and tree.

Click the units in the editor to make the Unit Processing framework mode. (The number of clicks required depends on the editor type .) The default editor for all cells is jtextfield. Although this can work well for many data types, it is not suitable for many other data types. Therefore, we do not support editing non-text information or setting a Special Editor for our jtable. For jtable, we can register an editor for a specific class type or column. Then, when the table runs on multiple corresponding types of units, the editor is used.

Note that jtextfield is used when no special editor is installed, although it is not suitable for the content.

18.6.1 tablecelleditor interface and defaultcelleditor class

The tablecelleditor interface defines the methods required for jtable to get the editor. Tablecelleditor has the same parameter list as tablecellrenderer. The hasfocused parameter is different. Because the unit is being edited, it is known that it has an input focus.

public interface TableCellEditor extends CellEditor {  public Component getTableCellEditorComponent(JTable table, Object value,    boolean isSelected, int row, int column);}

As described in Chapter 17th, defaultcelleditor provides interface implementation. He provides jtextfield as an editor, jcheckbox as another editor, and jcombobox as the third editor.

As shown in Table 18-13, the default editor is jtextfield in most cases. If the unit data can be converted into a string or a string, the class provides a constructor with the string parameter. The editor provides the text representation of the data as the initial editing value. Then we can edit the content.

18.6.2 create a simple Unit Editor

As a simple example of modifying non-string units in jtable, we can provide users with a set of fixed colors. Then, when you select a color, we can return the corresponding color value to the table model. Defaultcelleditor provides a jcombobox for this situation. After configuring the correct display color of the listcellrenderer in jcombobox, we will have a tablecelleditor to select the color. Figure 18-13 shows possible results.

Note: All options can be redefined at any time. We can use defaultcelleditor to use jcombobox as our editor.

The tablecellrenderer class for color column events and the listcellrenderer of jcombobox tablecelleditor shown in Figure 18-14 are displayed. Because of the similarity between the two Renderer components, their definitions are combined in a class.

Package swingstudy. ch18; import Java. AWT. color; import Java. AWT. component; import javax. swing. defaultlistcellrenderer; import javax. swing. jlabel; import javax. swing. jlist; import javax. swing. jtable; import javax. swing. listcellrenderer; import javax. swing. table. defaulttablecellrenderer; import javax. swing. table. tablecellrenderer; import swingstudy. ch04.diamondicon; public class combotablecellrenderer imple Ments listcellrenderer, tablecellrenderer {defaultlistcellrenderer listrenderer = new defaultlistcellrenderer (); extends tablerenderer = new ments (); Public void assumerenderer (jlabel Renderer, object Value) {If (value! = NULL) & (value instanceof color) {Renderer. seticon (New diamondicon (color) value); Renderer. settext ("");} else {Renderer. seticon (null); Renderer. settext (string) value) ;}}@ overridepublic component gettablecellrenderercomponent (jtable table, object value, Boolean isselected, Boolean hasfocus, int row, int column) {// todo auto-generated method stubtablerenderer = (defaulttablecellrenderer) tablerender Er. gettablecellrenderercomponent (table, value, isselected, hasfocus, row, column); configurerenderer (tablerenderer, value); Return tablerenderer;} @ overridepublic component aggregate (jlist list, object value, int index, boolean isselected, Boolean cellhasfocus) {// todo auto-generated method stublistrenderer = (defaultlistcellrenderer) listrenderer. getlistcellrenderercomponent (list, Value, index, isselected, cellhasfocus); configurerenderer (listrenderer, value); Return listrenderer ;}} to demonstrate the use of the new combined Renderer and display a simple table Unit Editor, A data model is created for programs displayed in the 18-15 list, and one column is color. After the Renderer is installed twice and the table cell editor is set, the table is displayed and the color can be edited. Package swingstudy. ch18; import Java. AWT. borderlayout; import Java. AWT. color; import Java. AWT. eventqueue; import javax. swing. defaultcelleditor; import javax. swing. jcombobox; import javax. swing. jframe; import javax. swing. jscrollpane; import javax. swing. jtable; import javax. swing. table. tablecelleditor; import javax. swing. table. tablecolumn; import javax. swing. table. tablemodel; public class editablecolorcolumn {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stub runnable runner = new runnable () {public void run () {color choices [] = {color. red, color. orange, color. yellow, color. green, color. blue, color. magenta}; combotablecellrenderer Renderer = new combotablecellrenderer (); jcombobox ComboBox = new jcombobox (choices); ComboBox. setrenderer (Renderer); tablecelleditor editor = new defaultcelleditor (ComboBox); jframe frame = new jframe ("editable color table"); frame. setdefaclocloseoperation (jframe. exit_on_close); tablemodel model = new colortablemodel (); jtable table = new jtable (model); tablecolumn column = table. getcolumnmodel (). getcolumn (3); column. setcellrenderer (Renderer); column. setcelleditor (editor); jscrollpane scrollpane = new jscrollpane (table); frame. add (scrollpane, borderlayout. center); frame. setsize (400,150); frame. setvisible (true) ;}}; eventqueue. invokelater (runner );}}

The table model used in this example and the next example is displayed in the 18-16 list.

package swingstudy.ch18; import java.awt.BorderLayout;import java.awt.Color;import java.awt.EventQueue; import javax.swing.DefaultCellEditor;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.table.TableCellEditor;import javax.swing.table.TableColumn;import javax.swing.table.TableModel; public class EditableColorColumn { /** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub Runnable runner = new Runnable() {public void run() {Color choices[] = {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN, Color.BLUE, Color.MAGENTA};ComboTableCellRenderer renderer = new ComboTableCellRenderer();JComboBox comboBox = new JComboBox(choices);comboBox.setRenderer(renderer);TableCellEditor editor = new DefaultCellEditor(comboBox); JFrame frame = new JFrame("Editable Color Table");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);TableModel model = new ColorTableModel();JTable table = new JTable(model); TableColumn column = table.getColumnModel().getColumn(3);column.setCellRenderer(renderer);column.setCellEditor(editor); JScrollPane scrollPane = new JScrollPane(table);frame.add(scrollPane, BorderLayout.CENTER);frame.setSize(400, 150);frame.setVisible(true);}};EventQueue.invokeLater(runner);} }

18.6.3 create a complex Unit Editor

Although the previous example demonstrates how to provide a definite set of options to the user using the list box tablecelleditor, providing a jcolorchooser as an option seems to be a better choice (at least, in color selection ). When defining our own tablecelleditor, we must implement a single tablecelleditor method to obtain the corresponding components. We must implement the seven methods of celleditor at the same time because they manage and notify a list of celleditorlistener objects and control when a unit can be edited. Starting with a subclass of abstractcelleditor makes it easier to define our own tablecelleditor.

By extending the abstractcelleditor class, only the getcelleditorvalue () method in the celleditor method needs to be customized for the editor. The preceding steps are implemented and a jbutton is provided. When you click the entire editor component, jcolorchooser is displayed. The source code of the custom editor is displayed in list 18-17.

package swingstudy.ch18; import java.awt.Color;import java.awt.Component;import java.awt.event.ActionEvent;import java.awt.event.ActionListener; import javax.swing.AbstractCellEditor;import javax.swing.JButton;import javax.swing.JColorChooser;import javax.swing.JTable;import javax.swing.table.TableCellEditor; import swingstudy.ch04.DiamondIcon; public class ColorChooserEditor extends AbstractCellEditor implementsTableCellEditor { private JButton delegate = new JButton(); Color savedColor; public ColorChooserEditor() {ActionListener actionListener = new ActionListener() {public void actionPerformed(ActionEvent event) {Color color = JColorChooser.showDialog(delegate, "Color Chooser", savedColor);ColorChooserEditor.this.changeColor(color);}};delegate.addActionListener(actionListener);}@Overridepublic Object getCellEditorValue() {// TODO Auto-generated method stubreturn savedColor;} public void changeColor(Color color) {if(color != null) {savedColor = color;delegate.setIcon(new DiamondIcon(color));}}@Overridepublic Component getTableCellEditorComponent(JTable table, Object value,boolean isSelected, int row, int column) {// TODO Auto-generated method stubchangeColor((Color)value);return delegate;} }

Figure 18-14 shows the running result of colorchoosereditor.

The sample program using the new colorchoosereditor is displayed in the 18-18 list. The example program reused the colortablemodel data model shown in 18-16 in the previous list. Setting colorchoosereditor involves setting tablecelleditor for corresponding columns.

package swingstudy.ch18; import java.awt.BorderLayout;import java.awt.EventQueue; import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.table.TableCellEditor;import javax.swing.table.TableColumn;import javax.swing.table.TableModel;  public class ChooserTableSample { /** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub Runnable runner = new Runnable() {public void run() {JFrame frame = new JFrame("Editable Color Table");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);TableModel model =  new ColorTableModel();JTable table = new JTable(model); TableColumn column = table.getColumnModel().getColumn(3); ComboTableCellRenderer renderer = new ComboTableCellRenderer();column.setCellRenderer(renderer); TableCellEditor editor = new ColorChooserEditor();column.setCellEditor(editor); JScrollPane scrollPane = new JScrollPane(table);frame.add(scrollPane, BorderLayout.CENTER);frame.setSize(400, 150);frame.setVisible(true);}};EventQueue.invokeLater(runner);} }

18.7 print a table

A new feature of jdk5.0 is also the easiest to use: The table printing feature. Through the simple jtable public Boolean print () throws printerexception method, we can print a large table on the printer. Even if we do not like to adapt the table to the default page width, we can expand columns on multiple pages.

To demonstrate this behavior, list 18-19 uses the basic jtable sample code to generate figure 18-1, add more rows to the table, and add a print button.

package swingstudy.ch18; import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.print.PrinterException; import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTable; public class TablePrint { /** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub final Object rows[][] = {{"1", "ichi - \u4E00"},{"2", "ni -\u4E8C"},{"3", "san - \u4E09"},{"4", "shi - \u56DB"},{"5", "go - \u4E94"},{"6", "roku - \u516D"},{"7", "shichi - \u4E03"},{"8", "hachi - \u516B"},{"9", "kyu - \u4E5D"},{"10","ju - \u5341"},{"1", "ichi - \u4E00"},{"2", "ni -\u4E8C"},{"3", "san - \u4E09"},{"4", "shi - \u56DB"},{"5", "go - \u4E94"},{"6", "roku - \u516D"},{"7", "shichi - \u4E03"},{"8", "hachi - \u516B"},{"9", "kyu - \u4E5D"},{"10","ju - \u5341"},{"1", "ichi - \u4E00"},{"2", "ni -\u4E8C"},{"3", "san - \u4E09"},{"4", "shi - \u56DB"},{"5", "go - \u4E94"},{"6", "roku - \u516D"},{"7", "shichi - \u4E03"},{"8", "hachi - \u516B"},{"9", "kyu - \u4E5D"},{"10","ju - \u5341"}};final Object headers[] = {"English", "Japanese"}; Runnable runner = new Runnable() {public void run() {JFrame frame = new JFrame("Table Printing");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);final JTable table = new JTable(rows, headers);JScrollPane scrollPane = new JScrollPane(table);frame.add(scrollPane, BorderLayout.CENTER);JButton button = new JButton("Print");ActionListener printAction =  new ActionListener() {public void actionPerformed(ActionEvent event) {try {table.print();}catch(PrinterException pe) {System.out.println("Error printing: "+pe.getMessage());}}};button.addActionListener(printAction);frame.add(button, BorderLayout.SOUTH);frame.setSize(300, 150);frame.setVisible(true);}};EventQueue.invokeLater(runner);} }

After clicking the print button, you will be prompted with a classic printer selection dialog box, as shown in 18-15.

Click the print button in the Print dialog box to start printing. A dialog box similar to the one shown in Figure 18-16 is displayed.

Indeed, JDK 5.0 is easy to print multi-page tables. The print () method returns a Boolean value, so that we can see whether the operation is disabled.

For users who want to query more print operations, jtable has multiple overloaded print () method versions. Similar to the simple print () method, they all throw printerexception.

One of the print () versions allows us to specify the print mode:

public boolean print(JTable.PrintModel printMode)

The jtable. printmodel parameter is an enumeration of fit_width and normal. If no parameter is specified for the print () version, the default value is fit_width.

The method of another version allows us to specify the header and footer:

public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat,  MessageFormat footerFormat

Messageformat comes from the java. Text package. One Parameter for formatting strings in the header and footer is the number of pages. To display the page number, include {0} where we want to display the page number in our formatted string }. Both are displayed in the middle of the page, while the header uses a slightly larger character. For demonstration, change the print () method call in 18-19 to the following format:

MessageFormat headerFormat = new MessageFormat("Page {0}");MessageFormat footerFormat = new MessageFormat("- {0} -");table.print(JTable.PrintMode.FIT_WIDTH, headerFormat, footerFormat);

The last print () version is a comprehensive version, so that we can configure the attributes required by the default printer without displaying the printer dialog box, for example, how many copies will be printed.

public boolean print(JTable.PrintMode printMode, MessageFormat headerFormat,MessageFormat footerFormat, boolean showPrintDialog,PrintRequestAttributeSet attr, boolean interactive)

If you do not want to interact with the printer, consider using the last version.

Conclusion 18.8

In this chapter, we discuss the internal details of the jtable component. We learned how to customize tablemodel, tablecolumnmodel, and listselectionmodel for jtable. We have gone deep into the abstraction and implementation of different table models. In addition, we discuss the internal elements of various table models, such as the tablecolumn and jtableheader classes. We also learned how to customize jtable display and editing by providing a custom tablecellrenderer and tablecelleditor. Finally, we learned how to print a table using the print () method.

In Chapter 19th, we will discuss the drag-and-drop architecture of the jfc/swing component set.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.