我想让我的可编辑JTables中的编辑器在开始编辑时选择单元格中的所有文本.我已经尝试了几个关于从TableCellEditor.getTableCellEditorComponent方法返回的组件上调用JTextComponent.selectAll()的东西.没有一件事,我试过工作.
在我最近的尝试中,我从Swing教程中修改了SimpleTableDemo类,以使用调用selectAll方法的自定义TableCellEditor.在调试器中,我可以看到selectAll()方法被调用,但是表格仍然进入编辑模式,而不选择单元格中的文本(或者可能在显示之前清除选择).该代码在下面.有人可以告诉我我哪里错了吗?
import javax.swing.DefaultCellEditor; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTree; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.text.JTextComponent; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class SimpleTableDemo extends JPanel { private boolean DEBUG = false; public SimpleTableDemo() { super(new GridLayout(1,0)); String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"}; Object[][] data = { {"Kathy","Smith","Snowboarding",new Integer(5),new Boolean(false)},{"John","Doe","Rowing",new Integer(3),new Boolean(true)},{"Sue","Black","Knitting",new Integer(2),{"Jane","White","Speed reading",new Integer(20),{"Joe","Brown","Pool",new Integer(10),new Boolean(false)} }; final JTable table = new SelectingTable(data,columnNames); table.setPreferredScrollableViewportSize(new Dimension(500,70)); table.setFillsViewportHeight(true); if (DEBUG) { table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { printDebugData(table); } }); } //Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); //Add the scroll pane to this panel. add(scrollPane); } private void printDebugData(JTable table) { int numRows = table.getRowCount(); int numCols = table.getColumnCount(); javax.swing.table.TableModel model = table.getModel(); System.out.println("Value of data: "); for (int i=0; i
解决方法
Table Select All Editor应该适合你.这是首选解决方案,因此您不必继续创建自定义编辑器.那就是包含整数的列只能接受整数.与您当前的代码
您的代码部分工作.如果您使用F2键开始编辑,则会选择文本.但是,当您使用鼠标并双击单元格时,第二个鼠标事件将传递给编辑器,因此插入符可以放置在您单击的位置,这将删除选择.解决方案是:
final JTextComponent jtc = (JTextComponent)c; jtc.requestFocus(); //jtc.selectAll(); SwingUtilities.invokeLater(new Runnable() { public void run() { jtc.selectAll(); } });