I'm trying to make a table that works like Excel. Meaning, when a user starts to insert data into the cells the content into them is selected and changed by the new data inserted.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Note that there is also another possibility, you can override JTable#prepareEditor like the following:
Creating a custom editor works fine if you only ever have String data in the table and only need a single editor. However, if you have multiple different types of data, like String, Integer, Double, currencies, percentages etc which all use a JTextField as an editor then you need to create multiple custom editors.
You can read up on the Table Select All Editor for another possible solution.
You should look at extJS. There is a pretty steep learning curve, though..
If your objective is to empty the cell when editing begins, no need to use
selectAll()
. Simply set value tonull
.Implementation example:
(overriding
getTableCellEditorComponent()
inDefaultCellEditor
)The solution above doesn't work when editing is started by a mouse click.
For some people the solution is to call selectAll() in an invokeLater() so that the text gets selected after the mouse events have been dispatched, but this isn't working for me (possibly because I'm using Substance look and feel?)
Swing internals get a mouseReleased() event later and change the caret again, as shown in this stack trace:
Here is my solution: Listen for caret position changes, and the first time the selection goes from all selected to none selected after cell editing has started, call selectAll() again. The caret listener can be installed by a custom cell editor as shown here, or in an overridden editCellAt() method in a custom JTable.
You can create a custom TableCellEditor for your table. This class will have an instance variable of a
TextField
, lets call ittextField
. Then thegetTableCellEditorComponent
method could look like this: