Java's JTABLE Usage

xiaoxiao2021-04-01  225

Java's JTABLE Usage

---------------------------- I found an article about JTABLE usage! --------- ------------------------------

Swing is a popular JTable class provides a simple mechanism for displaying large block data. JTable has a lot of things for data generation and editing, many of which can be customized to further enhance their functions. This article will guide you to enter JTable world step by step.

Listing A contains a simple example code, which illustrates the behavior of common JTABLE. Users can change the layout of the JTABLE, drag and drop it, or change their size by dragging the partition of the title.

These columns are saved in a string array: string [] columnNames = {"product", "number of boxes", "price"}; data is initialized and saved in a two-dimensional object array: Object [] [] Data = {{"Apples", New Integer (5), "5.00"}, {"ORANGES", New Integer (3), "6.00"}, {"pears", new integer (2), "4.00"} , {"Grapes", new integer (3), "2.00"},}; jtable is made of data and columnnames: jtable table = new jtable (data, columnnames);

View jtable

The height and width of the JTABLE are set according to the following method: Table.SetPreferredScrollableViewPorts Re (New Dimension (300, 80)); if a column of the JTable or the size of the JTable window is re-determined, then other columns will be reduced accordingly or Zoom in to adapt to new windows. Use setAutoResizeMode () method can control this behavior: table.setAutoResizeMode (int mode); mode integer field values ​​are possible: AUTO_RESIZE_OFFAUTO_RESIZE_NEXT_COLUMNAUTO_RESIZE_SUBSEQUENT_COLUMNSAUTO_RESIZE_LAST_COLUMNAUTO_RESIZE_ALL_COLUMNS

Default value

The default color of the unit grid coordinate line is Color.gray. To change the color of these checkered coordinate lines, you can use: Table.SetGridColor (color.black); you can change the height of the row with the following method: Table.SetRowHeight (INTPIXELHET); the height of each cell will be equal to The height of the line minus the distance between the line. By default, the selection of the foreground color and background colors of the content is determined by the desired implementation of swings. You can use the following method to change the selected color: table.setSelectionback; table.setSelection; you can also hide the checkered coordinate line of the cell, just like this: Table.SetShowhorizontallines (False); Table.SetShowverticalLines (false); Figure A shows a JTable hidden its horizontal coordinate line.

Figure A

Column width

The JTable component has several classes and interfaces for control table features. TableColumn will continue to track the width of the column and is responsible for the adjustment of the column, including maximum and minimum width. TableColumnModel manages the collection of TableColumns and the selection of columns. To set the width of a column, set a reference for the model of the table column. Then, obtain the desired TableColumn and call its setPreferRedWidth () method: TableColumnColumn = table.getColumnModel (). GetColumn (0); Column.SetPreferRedwidth (100); When the user is dragging, the column index does not happen change. GetColumn (0) method will return the correct column, no matter which place it appears on the screen. title

JTableHeader handles the display of the JTABLE title. You can subdivide JTABLEHEADER to get custom layout. For example, if your application requires a title across multiple columns, only JTABLEHEADER is simply subdividually divided into your jtable. You can specify whether the title of the title is allowed by setting a reference or calling its setReORDERLLOWED () method for the current JTABLE's JTABLEHEADER. Drag between the column headings and change the size. To reach this, you will use the setresizingAllowed () method: table.gettableHeader (). SetResizingAllowed (false);

Select mode

Under the default situation, the entire line is selected when the user selects a cell in JTABLE. There are a variety of ways to allow user to customize the way of choice. With the listSelectionModel interface, you can allow users to choose a single or multiple lines: Table.setSelectionMode (ListSelectionModel.single_selection); ListSelectionModel has the following fields:

Single_selection allows you to choose a line once. Single_Interval_seLection allows you to select a series of rows. Multiple_Interval_seLection also allows you to select adjacent columns, but with extended features. It allows users to use the [Ctrl] key for multiple mutual neighboring options (ie, selecting a row of not adjacent).

SetCellSelectionEnableD () method allows users to select a single cell at the same time: Table.setCellSelectionNableTenable; if set to yes, the setcellselectionenabled () method will also select the column while selecting rows and individual cells, if B shows.

Figure B

Edit cell

Our simple table allows users to edit any cell in the table. Listing B lists a table that allows for programmers to decide which cells can be edited. The first step is to create a custom TableModel: Class SimpleTableModel Extends AbstractTableModel {} data is encapsulated in TableModel. When JTABLE is initialized, custom TableModel is passed as a parameter to the JTABLE constructor instead of that two-dimensional Object arrays: simpleTableModelmyModel = new simpleTableModel (); jtable table = new jtable (mymodel); if you want the second column and the third column to edit, and turn the first column constant, then you have to Forced replacement TableModel's ISCELLEDITABLE () method: public booleaniscelleditable (int Row, INTCOL) {if (col == 0) {Return False;} else {return true;}}

You need to make sure that the user only enters an integer value. If you say, enter a value to the second column ("The number of boxes" this column) input value to replace the setValueat () method, and the verification logic includes in this new method. First, you have to check whether the columns are integers, and this column should only include integer values: if (Data [0] [Col] InstanceOf Integer &&! (Value InstanceOf Integer) {...} else {data [row] [col] ] = value;} then check if the inserted value is a integer. If it is not, then this field should not be updated, and you should display an error message: try {data [row] [color] = new integer ();} catch (Numberformatexcection E) {JOTIONPANE .ShowMessageDialog (SimpleTable.this, "Please enter Only Integer Values.");

background color

Listing c contains code for ColORTABLE.JAVA, which shows how to add color to JTABLE. You can join the background color to JTABLE by enforcing its preParerenderer () method: jtable table = new jtable (data, columnnames) {public component preparerenderer (INTCOL) {}}; then, insertion decision which columns There should be color and what color should be color: if (col == 2 &&! IScellSelected (Row, Col)) {Color BG = New Color (200, 100, 30); C.SetBackground (BG); C.setForeGround Be careful, when you change the cell background color, you should also make it easier to read more. Figure C shows a first column and the second column plus a color JTable.

Figure C

Everything is in master

Our example is just the foundation of other parts of JTable. By using these tools, you can quickly and easily control the formatting of the table generated by the Java application so that you can make your users don't touch obstacles when making normal use. -------------------------------------------------- -------------------------------------------------- ------------------------------

import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JPanel; import javax.swing.JTable; import java.awt.Color; import java.awt.GridLayout; import Javax.swing.table.tableColumn;

Public class jtabledemo {public static void main (String [] args) {/ * constructor has a lot of first introduces several: jtable () jtable (int NumRows, int NumColumns) jtable (Object [] [] Rowdata, Object [] Columnnames) * / jtable example = new jtable (); // can not see but existing jtable example2 = new jtable (8, 6); final object [] columnnames = {"Name", "Gender", "Home Address", // The column name is best to use Final to modify "Phone Number", "Birthday", "Work", "Income", "Marital Status", "Love Status"}}; object [] [] rowdata = {{"DDD", "Male", "Jiangsu Nanjing", "1378313210", "Student", "Parasitic", "Unmarried", "No"}, {"Eee", "Female", "Jiangsu" Nanjing "," 13645181705 "," XX / XX / 1985 "," Tutral Education "," Unknown "," Unmarried "," It seems to "}, {" FFF "," Men "," Jiangsu Nanjing "," 13585331486 "13585331486 "" 12/08/1985 "," car salesman "," unsure "," unmarried "," there is "}," ggg "," female "," Jiangsu Nanjing "," 81513779 "," XX / xx / 1986 "," Hotel Waiter "," Determine but unknown "," unmarried "," there "}, {" hhh "," male "," Jiangsu Nanjing "," 13651545936 "," XX / XX / 1985 " "" Students "," exile "," unmarried "," there is no "}}}}}}}}}}}}}; Friends.SetPreferRedscrollableViewPortSize (New Dimension (600, 100)); / / Set the size of the table Friends.setrowheight (30); // Set the height of each row of 20 f Riends.setrowheight (0, 20); // Set the height of the first row of 15 Friends.setrowMargin (5); // Set the distance Friends.setrowSelectionAllowed (TRUE) of the neighboring two lines; // Set whether you are selected The default is false friends.setSelectionBackground (color.white); // Sets the background color Friends.setSelectionForeground (Color.red) of the selected row; // Set the foreground of the selected row Friends.SetGridColor (Color.Black);

// Set the color of the grid line Friends.SelectAll (); // Select all row Friends.selectionElectionInterval (0, 2); // Set the initial selection line, here is the 1 to 3 row in the selection status Friends.clerateSerection ); // deselect Friends.SetDragenabled (false); // Do not understand this friends.setshowgrid (false); // Whether to display grid line friends.setshowhorizontallines (false); // Whether to display horizontal grid line Friends. SetShowVerticalLines (TRUE); // Whether to display vertical grid line Friends.SetValueat ("TT", 0, 0); // Set the value of a certain cell, this value is an object Friends.DOLYOUT (); friends. setBackground (Color.lightGray); JScrollPane pane1 = new JScrollPane (example1); // JTable is preferably added to the JScrollPane JScrollPane pane2 = new JScrollPane (example2); JScrollPane pane3 = new JScrollPane (friends); JPanel panel = new JPanel (new GridLayout (0, 1)); Panel.SetPreferredSize (New Dimension (600, 400)); panel.setBackground; panel.add (PANE1); panel.add (PANE3); JFRAME Frame = new jframe ("jtabledemo"); frame.setDefaultcloseOperation (jframe.exit_on_close); frame.setContentpane (PaME.PACK (); frame.show ();}}

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

New Post(0)