How to Mirror Edits across a Table Cell and Text Field
The desired behavior is akin to the mirrored text editing field provided in Excel when a given cell is selected, allowing more space to view the contents of the cell. I have a JTable with 5 columns and n rows. Column 2 holds expressions that can be arbitrarily long, thus I'd like to provide a separate JTextField to work with for editing the contents of the expression cell per row. The other fields are directly editable in the table. When the user clicks on a field in column 2, however, I want to send them to the text field. Any contents preexisting in the cell should be appear in the text field and additional edits in the text field should be mirrored in the table cell. Likewise开发者_如何学编程, if someone double-clicks on the cell and edits it directly, I want those changes reflected in the text field. Thus, the user can choose to edit in either space and both are updated. Ideally, they are updated per keystroke, but update upon hitting return is acceptable.
So, far I've got the JTable, TableModel, TableModelListener, JTextField, ListSelectionListener, and AbstractAction, working together to provide most of the functionality described above. I'm missing the reflection of direct table cell edits to the text field and per-keystoke updates.
Are their ideas on how best to construct this behavior?
Well, if you want to get data from the table to the cell then you add the code to your TableModel's setValueAt() function, which should run when the user changes the content in an editable cell. I don't think that will update per-keystroke though.
If you want to move data from the textbox to the table cell use code like this
myJTextField.getDocument().addDocumentListener(new MyDocumentListener());
Where MyDocumentListener
is an implementation of the javax.swing.event.DocumentListener
interface
That will get you per-keystroke updates from the box to the table. But for the other way around it's a bit trickier.
There are two ways you might be able to go about doing it
1) Add a key listener to the table, and when the user starts typing check to see what table element is active, and intercept keystrokes as they type. That's kind of messy, though.
2) Another option might be to try to grab or replace the component that the table is using to actually let the user make the changes. I think that JTable actually allows you to change the editor component if you dig around.
精彩评论