I created a simple mouse event. When the user clicks the JTable it will fetch the records in the JTable and display them in the JTextField. In this case I am trying to display the ID from the Table into the Text Field.
public void fetchRec() {
xtable.addMouseListener(new MouseAdapter() {
public void rowClicked(MouseEvent evt){
xtable =(JTable) evt.getSource();
int row = xtable.rowAtPoint( evt.getPoint() );
int column = xtable.columnAtPoint( evt.getPoint() );
String s=xtable.getModel().getValueAt(row, column)+"";
idLabelField.setText(s);
}
});
}
I am calling the method here but it keeps telling me that rowClicked method is unused. I don't understand how its unused? Everything else I am calling is working except this.
public void bookDimensions() throws Exception {
addTextLabels();
addTextFields();
addPanelButtons();
addRecord();
addTable();
fetchRec();
}
Turn on cell selection and listen to the selection model instead of mouse events. See java: how to select only one cell in a jtable and not the whole row
Related
I have implemented a custom TableModel that gets data from a database and then saves data to the database when a cell is edited.
Ie:
AbstractTableModel myModel = new AbstractTableModel(){
#Override public Object getValueAt(int r, int c){
//get value from the database, return it
}
#Override public setValueAt(Object val, int r, int c){
//update gui
//save change in database
}
//other methods here....
}
JTable tbl = new JTable(myModel);
This works fine, however in order for setValueAt() to be called you need to stop editing the cell, by default this only occurs when you select another cell, press enter, etc.
I then added the line:
tbl.putClientProperty("terminateEditOnFocusLost", true);
This means when I click away from the table setValueAt() is called and the database is updated, however if I edit a cell's value, then close the JFrame without the table losing focus or clicking another cell setValueAt() is never called and so the database is not updated, therefore any change you have made to that cell is lost.
Is there any way to prevent this and make the setValueAt() function be called?
I'm not sure if JTable can do the trick, but you can handle window closing event, where manually accept new value of editing cell.
frame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e) {
if(table.isEditing())
// This will dispose editor and call setValueAt() of your model as normally happens
table.getCellEditor().stopCellEditing();
}
});
I have a cell table showing some data. For each row, I want to have two columns which contain edit / delete buttons. When each button is clicked, it should be able to notify a listener which button was clicked (and preferably also be able to pass in the object that row is associated with).
How can I do this? Specifically, I know how to render a button, but how can I process the on-click event and pass in the object which the user clicked to edit or delete?
This is the standard approach:
myTable.addCellPreviewHandler(new Handler<MyObject>() {
#Override
public void onCellPreview(CellPreviewEvent<MyObject> event) {
if ("click".equals(event.getNativeEvent().getType())) {
if (event.getColumn() == 0 || event.getColumn() == 1) {
MyObject object = event.getValue();
Window.alert("Column clicked: " + event.getColumn());
}
}
}
});
This is a more efficient solution, because you only have one handler attached to a table, instead of trying to attach a handler to each button in each row.
I think you can make a foreach through all the rows in the celltable (I never worked with celltables)
And then you can add your own ClickHandler to the Button.
Something like that (not tested):
final int row = myrow; // add the row value or a object identifier or similar
Button delete_button = new Button("delete");
delete_button.addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
// Insert your delete funciton
delete(row);
}
});
You mentioned a Listener, Listener are depreciated, use Handler instead.
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.
Can someone help me with this listener?
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
if(e.getValueIsAdjusting()){
ListSelectionModel model = table.getSelectionModel();
int lead = model.getLeadSelectionIndex();
displayRowValues(lead);
}
}
private void displayRowValues(int rowIndex){
String country = "";
Object oCountry = table.getValueAt(rowIndex, 0);
country += oCountry.toString();
countryTxt.setText(country );
}
});
It's supposed to send data from cell in jtable (table) into a textfield (countryTxt) when one of the row's is selected, but it works only when I click on row and not when I'm cycling trough my table with arrow key's.
The problem is with this line:
if (e.getValueIsAdjusting()) {
Replace this with:
if (e.getValueIsAdjusting()) return;
This is a check for multiple selection events BTW.
If you comment out e.getValueIsAdjusting() it works.
http://docs.oracle.com/javase/6/docs/api/javax/swing/ListSelectionModel.html#setValueIsAdjusting(boolean)
I use the TableViewer to show informations in a table. The user can select one of the shown options by selecting one line of the table.
I want to create a table in matrix form, in which the user can not only select the line. It should be possible to select every item of the table, like row 2 column 3. For every item selection an action is called to handle this item as it is in the TableViewer.
As far as i now, i can add CellModifier and CellEditors to the line of Columns of the table, but the reference for the action is always the line object and not the selected TableItem.
Does somebody have an example how to create such a matrix inside a Composite?
I can create it by setting a GridLayout and adding the components in a for-loop, but than i get issues, when i want to redraw the Composite with new childrens. The TableViewer does already have this handling, so i dont want to implement it again.
I had the same problem a while ago and the only way I found to solve it was to register a mouse listener on the SWT table widget associated to the table viewer.
MouseListener columnSelectionMouseListener = new ColumnSelectionMouseListener();
getViewer().getTable().addMouseListener(columnSelectionMouseListener);
public class ColumnSelectionMouseListener implements MouseListener {
private TableColumn selectedColumn;
#Override
public void mouseDoubleClick(MouseEvent e) {
// Nothing to do here
}
#Override
public void mouseDown(MouseEvent e) {
table = (Table) e.widget;
TableItem item = table.getItem(new Point(e.x, e.y));
for (int i = 0; i < table.getColumnCount(); i++) {
TableColumn column = table.getColumn(i);
Rectangle bounds = item.getBounds(i);
if (bounds.contains(e.x, e.y)) {
selectedColumn = column;
}
}
}
#Override
public void mouseUp(MouseEvent e) {
// Nothing to do here
}
public TableColumn getSelectedField() {
return selectedColumn;
}
}
Then, for example in the viewer's selection listener, you can ask to the mouse listener which column was selected when the mouse has been pressed and combine that with the selected line coming from the viewer's selection to perform the appropriate action.
Hope this can help.
Manu
Maybe the following JFace snippet will help:
Snippet058CellNavigationIn34
Ingo