It is easy to create a JTable control. You can directly use its construction method. For example, you can create a table that displays 2D array data and display the column name: JTable (Object [] [] rowData, object [] columnNames)
Here, the two-dimensional array of rowData refers to the row content of the table, and the one-dimensional array of columnNames refers to the table title, so that you can create a simple table. To delete, add, and insert existing tables, we need to use the TableModel interface to create tables. In addition, java provides two classes: one is the AbstractTableModel abstract class and the other is the DefaultTableModel entity class. the former implements most of the TableModel methods, allowing users to flexibly construct their own table modes. The latter inherits the former class, which is the default table mode of java. DefaultTableModel implements the getColumnCount (), getRowCount (), and getValueAt () methods. therefore, in actual use, DefaultTableModel is much simpler and more often used than AbstractTableModel.
Here we use DefaultTableModel to construct a table model. The constructor of DefaultTableModel is as follows:
// Create a DefaultTableModel without any data.
DefaultTableModel ()
// Create a DefaultTableModel with the specified number of rows and columns.
DefaultTableModel (int numRows, int numColumns)
// Create a DefaultTableModel. The input data format is Object Array. The system automatically
// Call setDataVector () to set data.
DefaultTableModel (Object [] [] data, Object [] columnNames)
// Create a DefaultTableModel with the Column Header name and number of rows.
DefaultTableModel (Object [] columnNames, int numRows)
// Create a DefaultTableModel with the column Header name and number of rows.
DefaultTableModel (Vector columnNames, int numRows)
// Create a DefaultTableModel. The input data format is Vector. The system automatically calls
// SetDataVector () method to set data.
DefaultTableModel (Vector data, Vector columnNames ):
The DefaultTableModel class provides many useful methods, including getColumnCount (), getRowCount (), and getValueAt.
(), IsCellEditable (), setValueAt () and other methods can be used directly. DefaultTableModel also provides addColumn ()
With addRow () and other methods, we can add table data at any time.
For example, we want to add data:
// DefaultModel is the DefaultTableModel object. Data is a one-dimensional array to add data. addRow can only
// Add a row at a time. We can only add one piece of data at a time, so this statement is enough here.
DefaultModel. addRow (data );
It is a little troublesome to modify. The table does not provide one-time modification of all fields in a row. here we can use two methods.
. First, save all the data in the current table to a two-dimensional array, and then add
Replace the rows, return the array to the main window, and use setDataVector (Object [] [] dataVector, Object []
ColumnIdentifiers) to rewrite the array to the table. The second method is used first.
The table. getRowSelected () method is used to obtain the sequence number of the selected row. The sequence number is relative to the column above the table. Then use
Table. getValue (I, 0) to obtain the value in the first column of this row. The first column is the sequence number in our data. Pass this value to the data
In the modify window, after the modification is complete, return the modified one-dimensional array:
// First Delete the data in the row in the original table
DefaultModel. removeRow (I );
// Insert the new data to the sequence number of the selected row
DefaultModel. insertRow (I, data );
The former method looks more convenient than the latter method, but I prefer the latter method, because if the data volume is large, such
If there are 10000 data records, all the data needs to be re-written to the table for each modification. This will affect the speed.
You only need to delete a row and add a row. This will have an advantage in speed.
When it comes to queries, It is troublesome to look at the algorithms in the query class, but it is very simple to display the query results in the table. When querying
The result is saved to a two-dimensional array. The size of the two-dimensional array is dynamically specified, that is, its size root.
The number of queried results prevails. This is analyzed in the query class code. When the result is returned, we only need to use
The setDataVector () method can display data in a table.
It is a little troublesome to delete a table, because the number of data in the table is uncertain. For example, we have 10 data records, not necessarily in the table.
The 10 data records are displayed. You may query some of the data records and display them in the table. If you delete one of the 10 data records
The sequence number of the remaining data will also change accordingly. My practice here is to delete data from the file and display
Delete and detach data from a table. That is, first enter the delete class. In the method of this class, delete the data in the file first.
Division, and then sort. Then, the data displayed in the table is deleted and sorted, and the latter operation is returned.
. In this way, we can ensure data synchronization and reflect the deletion actions on the table in a timely manner. Same
The setDataVector () method displays the result in the table.
The following describes table events. To meet project requirements, you only need to implement one event, that is, double-click a field in the table and enter the data information in the pop-up window.
And modify the data. Here, I add an event with the right mouse click, that is, when you select a number of items in the table or
Directly right-click an item, and a shortcut menu is displayed, with the options of deleting and clearing. Select Delete to delete the selected
To clear all data in the table on the current screen. Note the difference between deleting and clearing data. Empty is not deleted
File data only serves as a clear screen.
Double-click table event: DefaultTableModel the default table can be edited. When we double-click a field in the table
This will automatically trigger the event to modify this field, so it will be very difficult for us to add our own double-click event, at least I have not found any way
After double-clicking, You can trigger the field modification event and respond to the event we added. If anyone knows the method, do not
I 'd like to thank you first. Before I know a better solution, I can only use DefaultTableModel to create a table model.
Every field cannot be edited. You can reload the isCellEditable method of DefaultTableModel. This method returns true by default,
That is, editable. We can change it to false to achieve the desired effect. For example:
Class MyTable extends DefaultTableModel {
Public MyTable (Object [] [] data, Object [] head ){
Super (data, head );
}
Public boolean isCellEditable (int row, int column ){
Return false;
}
}
Then, you can use MyTable in the program to create an object instead of DefaultTableModel to make the table uneditable. Of course
When the model is created using the abstract class AbstractTableModel, the above method is not required, because this abstract class defaults
The created table cannot be edited. (Note: The table mentioned here cannot be edited. It is not set by the setEnabled () method in the table.
Edit attributes. The data items in the entire table cannot be selected.
.) In this case, you only need to add the mouse listener and determine whether e. getClickCount () is equal to 2 to trigger double-click.
. If you want to improve the program, you can add Timer to make a time judgment, that is, when you click a certain item, there are many listeners
If 2nd clicks are not performed after a few milliseconds, they are considered as clicks. Otherwise, they are double-clicked. However, this is enough. Java
Double-click events are really troublesome.
Right-click an event: Right-click an event to make a judgment. When multiple data items are selected with the left-click
Right-click the selected data items, and the program will operate the selected data items, and the focus of the selected data items is not
Will be lost. This is the case of multiple choices. If you right-click a data item that has not been selected, the right-click menu is also displayed, and the focus changes
Right-click the data item, which is converted from multiple choices to single choice. It is really troublesome to express it in words. It is very easy to use code.
Such:
// Obtain the row number of the data item pointed to by the cursor
Int I = table. rowAtPoint (e. getPoint ());
// Determine whether the current row is selected
If (! Table. isRowSelected (I ))
{
// If not selected, move the focus to the data item
Table. setRowSelectionInterval (I, I );
}
// Right-click or not
If (SwingUtilities. isRightMouseButton (e ))
{
// The menu is displayed at the coordinates of the current mouse.
JPopupMenu. show (e. getComponent (), e. getX (), e. getY ());
}
The rest are all selected, all deleted, and clearing these functions is relatively simple. If you select all data items, use getRowCount () to obtain the total number of data items in the current table. Use the setRowSelectionInterval () method. The parameter value is 0 and the total number of data items is obtained.
All data in the current table. To delete all data, you must first call the delete class to delete all data in the file, and then use
Use the setDataVector () method to set the first parameter array to an empty array. If the file is cleared, the file will not be deleted.
The method is the same as Clearing table data.
The operation code for data is very simple. A large number of setProperty () and getProperty () methods are used. These commonly used methods
I encapsulate them into a class so that they can interact with the operation. The most troublesome part of the entire program is the deletion function. Especially before
As mentioned above, the data displayed in the table is updated, and the text cannot be clearly stated. You should paste the code I wrote first.
Method may be a very stupid method, but limited to its own capabilities, you can only do this.
The code may be abstract. Let's take a practical example. For example, we have 10 data records, each of which has 13 fields, and then
The first field of each data record is the serial number, which indicates that after a data record is deleted, the serial number of all data after the data record is pushed forward.
Move one digit and delete Multiple Digits at the same time. The serial numbers of Multiple Digits may not be consistent. For example, there are only 10 entries in the screen table.
Five of the data records are numbered 1, 3, 5, 8, and 9. At this time, we need to delete the data numbered 3 and 8 at the same time.
The number of the remaining data on the screen should be, 7. The following code implements this function.
// A method for deleting a class. This parameter is a data transmission class used to transmit data. After the method is executed, an array of results is returned.
Public Object [] [] removeTableData (DataStorage storage ){
// Obtain the first field of the selected data item, that is, the sequence number of the selected data. One
Array to save them, such as 5 and 8.
Object [] data = storage. getData ();
// Obtain all fields of all data items in the current table. Therefore, it is a two-dimensional array.
Object [] [] tableData = storage. getTableData ();
// Length counter, because after each item is found, the length of all data should be reduced by one digit, and the counter is accumulated.
Int delColumn = 1;
// Compare the sequence number of the selected data item with the sequence number of all data items. The selected sequence number array starts from the last element in the array.
Comparison
For (int j = data. length-1; j> = 0; j --)
{
// The sequence number of all data in the table, starting from the last digit of the selected sequence number array and the last digit of the sequence number array of all data in the table
Relatively
For (int I = tableData. length-delColumn; I> = 0; I --)
{
// If the two are equal, the sequence number is used as the starting point of the loop, and the next data item overwrites the previous data item.
If (tableData [I] [0]. equals (data [j])
{
For (; I <tableData. length-delColumn; I ++)
{
For (int column = 0; column <13; column ++)
{
TableData [I] [column] = tableData [I + 1] [column];
}
// The serial number-1 of the overwritten data item
Int index = Integer. parseInt (tableData [I] [0]. toString ());
Tabledata [I] [0] = string. valueof (index-1 );
}
// The total length of data after the item is deleted should be reduced by 1 and compared from the next data
Delcolumn ++;
Break;
}
}
}
// Create an array. The length of the array is the number of data remaining after the selected data is deleted.
Object [] [] passdata = new string [tabledata. Length-Data. Length] [13];
// In fact, we did not actually delete a certain data, but overwritten the subsequent data in sequence. Therefore, we need to create
A new array, which only leaves the data items we need
// The excess data will be discarded.
For (INT I = 0; I <passdata. length; I ++)
{
For (Int J = 0; j <13; j ++)
{
Passdata [I] [J] = tabledata [I] [J];
}
}
Return passdata;
}
Finally, put the returned array in the table. This method looks complicated, but I can only think of this method. Trust
There are simpler ways to implement this function. Of course, the database method is not mentioned. The summary of the entire project is almost here.
. If you have time, I will continue to expand the functions of this project. For example, if multiple users are added and too much data is processed
Wait time, you can add a process bar to display the progress completion percentage. If I have the opportunity, I will study SWT,
Using SWT to complete the interface of the program, I believe it will be another exciting thing. Let's make a summary later.
A jcombobox class showing the date is attached. This class fully inherits jcombobox, obtains the local time through the date class, and then formats it, it is displayed in the jcombobox drop-down list in the format of yyyy, mm, DD. If you need to, you can directly Save the following code as a Java file. After importing the package, directly create an object of this class and you can add it to the interface.
The jcombobox property is the same as the property of this control.
Import java. Text. simpledateformat;
Import java. util. calendar;
Import java. util. gregoriancalendar;
Import javax. Swing. jcombobox;
Public class comboboxdate extends jcombobox {
Public comboboxdate (){
Super (getarray ());
}
Private static Object [] getArray (){
// Declare the Object array to save the formatted date string
Object [] editDate = new String [1];
Calendar date = new GregorianCalendar ();
// Format the obtained local time
SimpleDateFormat format = new SimpleDateFormat ("dd, yyyy ");
EditDate [0] = format. format (date. getTime ());
Return editDate;
}
}
Import java. awt. BorderLayout;
Import javax. swing. JFrame;
Import javax. swing. JScrollPane;
Import javax. swing. JTable;
Import javax. swing. table. AbstractTableModel;
Import javax. swing. table. TableModel;
Public class tableTest {
Private static JTable table;
Public static void main (string [] ARGs ){
Tabframe frame = new tabframe ();
Frame. setdefaclocloseoperation (jframe. exit_on_close );
Frame. setvisible (true );
}
}
Class tabframe extends jframe {
Private jtable table;
Public tabframe (){
Settitle ("table model test ");
Setsize (400,300 );
Getcontentpane (). setlayout (null );
Final jscrollpane scrollpane = new jscrollpane ();
Scrollpane. setbounds (65, 10,255,201 );
Getcontentpane (). Add (scrollpane );
Tablemodel model = new investmenttablemodel (30, 5, 10); // create a table model object
Table = new jtable (model); // create a table and load the table model.
ScrollPane. setViewportView (table); // Add a table to the scroll box.
}
}
/**
* Table model class
*/
Class InvestmentTableModel extends acttablemodel {
Private int years;
Private int minRate;
Private int maxRate;
Private static double maid = 100000.0;
Public InvestmentTableModel (int y, int r1, int r2 ){
Years = y;
MinRate = r1;
MaxRate = r2;
}
/**
* Set the number of rows
*/
Public int getRowCount (){
Return years;
}
/**
* Set the number of Columns
*/
Public int getColumnCount (){
Return maxRate-minRate + 1;
}
/**
* Fill in cell values
*/
Public Object getValueAt (int r, int c ){
Double rate = (c + minRate)/100.0;
Int nperiods = r;
Double futurBalance = INITIAL_BALANCE * Math. pow (1 + rate, nperiods );
Return String. format ("%. 2f", futurBalance );
}
/**
* Set the column name
*/
Public String getColumnName (int c ){
Return (c + minRate) + "% ";
}
}