I have enabled tooltips in my JTable by overriding the JComponent method that the JTable inherits:
public String getToolTipText(MouseEvent e) { ... }
Now, suppose a user hovers over a cell, the tooltip appears, and then (s)he starts editing the cell, I want to forcefully dismiss the tooltip.
Currently, the tooltip just hangs around until the value that I specified using ToolTipManager#setDismissDelay expires. The tooltip can sometimes obscure the view of the cell being edited which is why I want to dismiss it the moment any cell on the table goes into edit mode.
I tried the following approach (this is pseudo-code)
public String getToolTipText(MouseEvent e)
{
if(table-is-editing)
return null;
else
return a-string-to-display-in-the-tooltip;
}
Of course, this only had the effect of NOT showing tooltips of the table is ALREADY in edit mode. I knew this wouldn't work, but it was more of a shot in the dark.
You can show/hide a tooltip by using code like:
//Action toolTipAction = component.getActionMap().get("postTip");
Action toolTipAction = component.getActionMap().get("hideTip");
if (toolTipAction != null)
{
ActionEvent ae = new ActionEvent(component, ActionEvent.ACTION_PERFORMED, "");
toolTipAction.actionPerformed( ae );
}
You couuld probably override the prepareCellEditor(...) method of JTable to add this code and it should hide any tooltip before displaying the editor.
Edit:
In response to Kleopatra's comment I then add the following to make sure the Action is added to the ActionMap:
table.getInputMap().put(KeyStroke.getKeyStroke("pressed F2"), "dummy");
ToolTipManager.sharedInstance().registerComponent( table );
Was about to comment "something wrong with your" - but remembered a use case when not hiding the Tooltip on starting edits may happen :-)
Some facts:
tooltips are hidden on mouseExit and on focusLost the component which is registered with the ToolTipManager
when starting an edit and the editing component gets focus so the tooltip is hidden automatically
by default, JTable does not yield focus to the editing component is the editing is started by typing into the cell (as opposed by double-click or F2): in this case no focusLost is fired and consequently the tooltip not hidden
the ToolTipManager indeed installs a hideAction which might be re-used (as #camickr mentioned). But - that action is installed only if the component has a inputMap of type WHEN_FOCUSED. Which is not the case for JTable (all its bindings are in WHEN_ANCESTOR)
So it requires a handful of tweaks to implement the required behaviour, below is a code snippet (note to myself: implement in SwingX :-)
JTable table = new JTable(new AncientSwingTeam()) {
{
// force the TooltipManager to install the hide action
getInputMap().put(KeyStroke.getKeyStroke("ctrl A"),
"just some dummy binding in the focused InputMap");
ToolTipManager.sharedInstance().registerComponent(this);
}
#Override
public boolean editCellAt(int row, int column, EventObject e) {
boolean editing = super.editCellAt(row, column, e);
if (editing && hasFocus()) {
hideToolTip();
}
return editing;
}
private void hideToolTip() {
Action action = getActionMap().get("hideTip");
if (action != null) {
action.actionPerformed(new ActionEvent(
this, ActionEvent.ACTION_PERFORMED, "myName"));
}
}
};
Check out this JTable tutorial. In particular this webstart. There are two editable columns with tooltips - 'Sport' and 'Vegetarian' work just fine. Are you using any custom cell renderers?
This worked for me and seems simpler than using an action:
ToolTipManager.sharedInstance().mouseExited(new MouseEvent(myJframe, 0, 0, 0, 0, 0, 0, 0, 0, false, 0));
This seems to hide any tooltip shown inside the specified JFrame.
With JDK 1.6, when a cell tooltip is being displayed, the user cannot extend the range of selected rows using the keyboard. The solution presented above worked very nicely for that problem as well. Here is the code:
public class ToolTipTable extends JTable
{
/**
* Constructor
*/
public ToolTipTable()
{
super();
// force the TooltipManager to install the hide action
getInputMap().put(KeyStroke.getKeyStroke("ctrl A"),
"just some dummy binding in the focused InputMap");
ToolTipManager.sharedInstance().registerComponent(this);
//hide the tool tip when row selection changes
this.getSelectionModel().addListSelectionListener(
new ListSelectionListener()
{
#Override
public void valueChanged(ListSelectionEvent e)
{
hideToolTip();
}
});
}
/**
* Make the cell tool tip show the contents of the cell. (Useful if the
* cell contents are wider than the column.)
*/
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row,
int column)
{
Component c = super.prepareRenderer(renderer, row, column);
if (c instanceof JComponent)
{
JComponent jc = (JComponent) c;
Object valueObj = getValueAt(row, column);
if (valueObj != null)
{
jc.setToolTipText(getValueAt(row, column).toString());
}
}
return c;
}
/**
*
*/
private void hideToolTip()
{
Action action = getActionMap().get("hideTip");
if (action != null)
{
action.actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, "myName"));
}
}
}
Related
I'm trying to implement a JTable which has to obey the following rules:
Only the 3'rd column's cells can be edited.
When double clicking any cell in row X, the 3'rd column of row X will start edit.
Whenever start editing a cell, the text inside of it will be selected.
I have a FileTable which extends JTable. In its constructor I have this lines:
getColumnModel().getColumn(2).setCellEditor(new FileTableCellEditor());
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if (e.getClickCount() == 2){
int row = rowAtPoint(e.getPoint());
editCellAt(row, 2);
}
}
} );
My FileTableCell editor is as follows:
public class FileTableCellEditor extends DefaultCellEditor {
public FileTableCellEditor() {
super(new JTextField());
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
final JTextField ec = (JTextField) editorComponent;
String textValue = (String)value;
ec.setText(textValue);
SwingUtilities.invokeLater( new Runnable() {
#Override
public void run() {
ec.selectAll();
}
});
return editorComponent;
}
}
My problem is when I double click on a cell which is not from the 3'rd column, The text edited on the 3'rd columns is not highlighted as selected text.
picture http://www.nispahit.com/stack/tableNotHighlight.png
This is very odd to me, because I know the text is selected. When I write something it removes the text that was in that cell before. It just doesn't what is selected.
Oddly, when I double click the 3'rd column cell itself, it does highlight the selection.
picture http://www.nispahit.com/stack/tableHighlight.png
Can someone pour some light?
Thanks!
You can try the Table Select All Editor approach. Don't forget to check out the Table Select All Renderer.
Your JTextField does not highlight the selection because it is not focused. Just add a ec.requestFocus(); right after ec.selectAll();. Then it works as expected.
Explanation: When you click on the editable column Swing will start cell editing (independently of your double-click listener) and forward the initiating event to the component. So the JTextField receives a click and will request focus. When you click on a different column, only your MouseListener initiates cell editing and the event will not get forwarded. (Forwarding the event would not help anyway as the click is outside the text field.) So you have to request the focus manually.
I am showing some results in a JTable that consists of 2 columns.
File - Result
I implemented a JPopupMenu which displays a copy entry, and I try to copy the value of the cell, where I right-clicked.
filelistTable.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e))
{
TablePopupMenu popup = new TablePopupMenu(filelistTable, e.getPoint());
filelistTable.setComponentPopupMenu(popup);
}
}
});
--
public TablePopupMenu(JTable table, Point p) {
this.table = table;
this.p = p;
JMenuItem mntmKopieren = new JMenuItem("Kopieren");
mntmKopieren.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
copyCellToClipboard();
}
});
add(mntmKopieren);
}
public void copyCellToClipboard()
{
int r = table.rowAtPoint(p);
int c = table.columnAtPoint(p);
System.out.println(table.getValueAt(table.convertRowIndexToView(r),
table.convertRowIndexToView(c)));
StringSelection entry = new StringSelection(table.getValueAt(table.convertRowIndexToView(r),
table.convertRowIndexToView(c)).toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents( entry, this );
}
Anyhow, this only works for a small number of tests.
Did I do something wrong or something missing? It looks to me, as if the cell will not even get choosen correctly.
Two thingies are slightly off:
setting the componentPopup in the clicked is too late in the sequence of mouseEvents (popups are typically triggered on pressed or released which happen before the click)
the value is taken from the incorrect cell: all coordinates in a JTable are in view coordinate system, converting them to view coordinates will be completely off
That said: getting cell-coordinate related context is poorly supported. Often, the best bet is to (code snippet below)
override getPopupLocation(MouseEvent) and store the location somewhere
implement a popup/action to access the location
Fails if (as should be done in a well-behaved application), the popup could be triggered by keyboard: if that's the case, you'll need to provide some other marker (f.i. the focused cell) to act on.
final String popupLocation = "table.popupLocation";
final JTable table = new JXTable(new AncientSwingTeam()) {
#Override
public Point getPopupLocation(MouseEvent event) {
// event may be null if triggered by keyboard, f.i.
// thanks to #Mad for the heads up!
((JComponent) event.getComponent()).putClientProperty(
popupLocation, event != null ? event.getPoint() : null);
return super.getPopupLocation(event);
}
};
JPopupMenu popup = new JPopupMenu();
Action printLocation = new AbstractAction("print cell") {
#Override
public void actionPerformed(ActionEvent e) {
Point p = (Point) table.getClientProperty(popupLocation);
if (p != null) { // popup triggered by mouse
int row = table.rowAtPoint(p);
int column = table.columnAtPoint(p);
LOG.info("" + table.getValueAt(row, column));
} else { // popup triggered otherwise
// could choose f.i. by leadRow/ColumnSelection
...
}
}
};
popup.add(printLocation);
table.setComponentPopupMenu(popup);
Edit (triggered by Mad's comment):
You should be checking MouseEvent.isPopupTrigger as the trigger point is platform dependent. This does mean you need to monitor mousePressed, mouseReleased and mouseClicked
No, that's not needed (just checked :-): the mechanism that shows the componentPopup in response to a mouseEvent - happens in BasicLookAndFeel.AWTEventHelper - only does so if it is a popupTrigger.
By reading the api doc (should have done yesterday ;-) again, it turns out that the method is called always before showing the componentPopup, that is also if triggered by other means, f.i. keyboard. In that case the event param is null - and the original code would blow. On the bright side, with that guarantee, all the logic of finding the target cell/s could be moved into that method. Didn't try though, so it might not be feasable (f.i. if then the location should be based on the leadRow/ColumnSelection that might not yet be fully handled at that time)
I have a JTable with editable cells. When I click in a cell, it enters edit mode; the same happens when I'm moving through cell using the directional arrows.
Now I want to select the cell instead of start editing, and edit the cell only when the Enter key is pressed.
If any other information is needed, please just ask for it.
Edit: Action for Enter key
class EnterAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
JTable tbl = (JTable) e.getSource();
tbl.editCellAt(tbl.getSelectedRow(), tbl.getSelectedColumn());
if (tbl.getEditorComponent() != null) {
tbl.getEditorComponent().requestFocus();
}
}
}
Now this is for left arrow action the rest of 3 are not hard to deduce from this one:
class LeftAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
JTable tbl = (JTable)e.getSource();
tbl.requestFocus();
tbl.changeSelection(tbl.getSelectedRow(), tbl.getSelectedColumn() > 0 ? tbl.getSelectedColumn()-1:tbl.getSelectedColumn(), false, false);
if(tbl.getCellEditor()!=null)
tbl.getCellEditor().stopCellEditing();
}
}
And this is how you bind this actions:
final String solve = "Solve";
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(enter, solve);
table.getActionMap().put(solve, new EnterAction());
final String sel = "Sel";
KeyStroke arrow = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(arrow, sel);
table.getActionMap().put(sel, new LeftAction());
Oh,i almost forgot,to select the cell instead of edit on Mouse Click:
public static MouseListener mAdapterTable = new MouseListener()
{
#Override
public void mousePressed(MouseEvent e)
{
JTable tbl=((JTable)e.getComponent());
if(tbl.isEditing())
{
tbl.getCellEditor().stopCellEditing();
}
}
#Override
public void mouseClicked(MouseEvent e) {
JTable tbl=((JTable)e.getComponent());
if(tbl.isEditing() )
tbl.getCellEditor().stopCellEditing();
}
#Override
public void mouseReleased(MouseEvent e) {
JTable tbl=((JTable)e.getComponent());
if(tbl.isEditing() )
tbl.getCellEditor().stopCellEditing();
}
};
The EventListner must be added to table like so:
table.addMouseListener(mAdapterTable);
Use Key Bindings for this. Most Look & Feel implementations already bind F2 to the table's startEditing action, but you add a different binding:
tree.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "startEditing");
This will effectively replace the previous binding of Enter to the table's selectNextRowCell action.
Here is what i would do:
First enable the single cell selection for the JTable
Create a KeyAdapter or KeyListener for the JTable or for the JPanel,
what contains your table.
In the KeyAdapter's keyPressed() method enter the edit mode of the
selected cell, something like this:
http://www.exampledepot.com/egs/javax.swing.table/StopEdit.html
You can check in the keyPressed() method, if the user pressed the right button for editing. I'm not sure, if the normal (double click) editing is disabled in your table, then what happens, if you try to edit it programmatically, but if it doesn't work, then you can enable the editing on the selected cell, when the user presses the edit button, then when he/she finished, disable it again.
I´m trying to implement an undo (and redo) function for an editable JTable with the default components. The JTable has an extra class to specify its properties called SpecifiedJTable.
To do so I wanted to grab the moment when a cell is doubleclicked (i.e. the moment when a cell is chosen/marked to be edited) to push the information in the cell and its coordinates onto the stack.
This should be done by a MouseListener ...at least that was my idea.
I tried this (standing in the constructor of my SpecifiedJTable class)
class JTableSpecified extends JTable {
private static final long serialVersionUID = 1L;
private int c; // the currently selected column
private int r; // the currently selected row
public JTableSpecified(String[][] obj, String[] columnNames) {
super(obj, columnNames); // constructs the real table
// makes that you can only select one row at a time
this.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
// makes that columns are not squeezed
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// forbids to rearrange the columns
getTableHeader().setReorderingAllowed(false);
// adds action listener
this.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
r = getSelectedRow();
c = getSelectedColumn();
// get the String at row r and column c
String s = (String) getValueAt(r, c);
if (jobDisplayed) jobSwitch(c, s);
else resSwitch(c, s);
}
});
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
System.out.println("test");
}
}
});
}
}
but somehow the clickCounter doesn´t want to reach anything that´s higher than 1.
I am glad about any answer and help. Thanks.
The problem you are experiencing is related to use of mouseClicked() rather than using mousePressed(). In this case it appears to be very hard to increase the click counter, yet still it is possible. It took me lots of clicking and also mouse movement to increase the click counter over 1. You could try it by yourself, in your code. To get the counter over 1 you need to go crazy on the mouse by pressing & releasing fast while moving the mouse from cell to cell at the same time (or maybe I was just luckily clicking between the cells?).
As you can see in this fully working sample, made from your code, two mouse presses, using the mousePressed() method are being detected just fine.
public class JTableSpecified extends JTable {
private static final long serialVersionUID = 1L;
public JTableSpecified(String[][] obj, String[] columnNames) {
super(obj, columnNames); // constructs the real table
// makes that you can only select one row at a time
this.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
// makes that columns are not squeezed
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
// forbids to rearrange the columns
getTableHeader().setReorderingAllowed(false);
// adds action listener
this.getModel().addTableModelListener(new TableModelListener() {
#Override
public void tableChanged(TableModelEvent e) {
}
});
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
System.out.println("test");
}
System.out.println("e.getClickCount() = " + e.getClickCount());
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JPanel panel = new JPanel();
panel.add(new JTableSpecified(new String[][]{{"oi", "oi2"}, {"oi3", "oi4"}}, new String[]{"Col1", "Col2"}));
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(panel);
f.pack();
f.setVisible(true);
}
});
}
}
Conclusion: Maybe you in fact want to use the mousePressed() method?
This answer extends Boro´s answer.
To catch every case that enables the user to edit the table I will also need to add a KeyListener for F2 (which has the same effect as double clicking onto a cell) and disable the automatic cell editing by pressing any key.
I just added it to the constructor right behind the mouseListener (see above)
// forbids the editing by striking a key
this.putClientProperty("JTable.autoStartsEdit", Boolean.FALSE);
// keyListener to react on pressing F2 (key code 113)
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 113) System.out.println("test");
}
});
The BasicTableUI is responding to the double-click by going into an edit mode on the cell that was double-clicked. It does lots of complicated stuff, part of which involves creating a JTextField (or other component) to allow the data to be edited, and then preventing the mouse click event from propagating any further.
If your table, or that table cell, is not editable, you can easily capture mouse events with click count 2, 3, 4, .... But since you want your table to be editable, you need a different approach.
One idea would be to override JTable.editCellAt()
A better idea is to forget about messing with the JTable and instead listen for data changes on the table model itself.
the error in the code is that the mouseClicked method is called as soon as the first click takes place. when a double click takes place the mouseClicked method is called again. you can place a static variable (or a class variable) for the earlier click event storing the time (using the e.getWhen() method).
Check for the time difference and if it's small enough, execute your actions (I'd suggest calling a doubleClick method).
you may have to implement mouse listener in your class JTableSpecified since a static variable might not be placed in your existing code.
I am using an editable JTable that contains a column named Subject. When the first row is empty and the user clicks on a subject cell to add new task, by default, the user has to click twice to make the cell editable. I want to make it editable on single-click and have it open another form on double-click. I have tried MouseListener but have not been able to solve it. Is there a way to solve this problem? If so, what is it?
My code:
class mouseRenderer extends DefaultTableCellRenderer {
JLabel lblcell = new JLabel();
public Component getTableCellRendererComponent(JTable table, Object obj, boolean isSelected, boolean hasFocus, int row,
int column) {
ttable.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
selrow = ttable.getSelectedRow();
selcol = ttable.getSelectedColumn();
if(e.getClickCount() == 1) {
if(selrow == 0) {
lblcell.setText("");
}
}
}
});
return lblcell;
}
}
For the one-click to edit, you could try the 'setClickCountToStart()' method of the celleditor used in your jtable.
You can try to create a custom CellEditor like this one and set it with setCellEditor()
public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
public boolean isCellEditable(EventObject evt) {
if (evt instanceof MouseEvent) {
int clickCount;
// For single-click activation
clickCount = 1;
// For double-click activation
clickCount = 2;
// For triple-click activation
clickCount = 3;
return ((MouseEvent)evt).getClickCount() >= clickCount;
}
return true;
}
}
The MouseListener is the way to go for capturing double clicks on a row. It should work fine.
As far as one-click to edit, you might want to select rows using a MouseMotionListener and let the JTable take the single-click to edit. Another option might be to use a MouseListener to detect the cell that was clicked, but that is getting a little messy.