Reading the Data of a Highlighted Jtable Row - java

I have a JTable with rows of Data
I have this event that listen every time a row got mouse clicked
private void tablePOMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row1 = tablePO.getSelectedRow();
cellA = tablePO.getValueAt(row1, 0).toString();
cellB = tablePO.getValueAt(row1, 1).toString();
cellC = tablePO.getValueAt(row1, 2).toString();
cellD= tablePO.getValueAt(row1, 3).toString();
cellE = tablePO.getValueAt(row1, 4).toString();
cellF = tablePO.getValueAt(row1, 5).toString();
cellG = tablePO.getValueAt(row1, 6).toString();
cellH = tablePO.getValueAt(row1, 7).toString();
} catch (Exception e) {
}
}
variable cellA-H are all Strings.
its working good, but now I want to change it, I dont want the user to have the need to use the mouse, so instead, I want the user just select the row with using either UP/DOWN arrow to navigate the rows and put the selected row under the highlight, but I have no Idea how I am able to achieve it, reading the data from highlighted/selected row by using the UP/DOWN Keys (Not by pointing the row with mouse click).

Add a ListSelectionListener to the table.
An event will be generated whenever the row selection changes whether you use the mouse or the keyboard.
Read the section from the Swing tutorial on How to Write a ListSelectionListener for more information and working examples.

Related

update jtable model after filtering

I want to apply the filter to the JTable.
String text = textField.getText();
rowSorter = new TableRowSorter<>(tableModel);
this.getjTable1().setRowSorter(rowSorter);
this.getjTable1().removeAll();
if (text.trim().length() == 0) {
rowSorter.setRowFilter(null);
} else {
//String regex = String.format("^%s$", text);
if(jCheckBoxExtract.isSelected()){
text="^"+text+"$";
}
else{
if(!text.contains(".")||text.contains("$"))text="^"+text;
}
RowFilter rowFilter = RowFilter.regexFilter(text, 1);
rowSorter.setRowFilter(rowFilter);
}
this.getjTable1().repaint();
this code work but now, if I want to get a value in jtable, the model doesn't update. The model use in jtable is always the old model but not the new model after filter.
to get the proper value do this whenever you need the row from the table:
model.getSelectedEntry(table.convertRowIndexToModel(table.getSelectedRow()));

Having a String or int with a binding to a Property

I need to make a programm in JavaFX where I need to manage a movie library. I have a tableview that is filled by an observable list. Then I made bindings between the Properties and the Textboxes or Labels next to the tableview. Now the problem is, I have also pictures that are related to the movies, like cinema posters. and at the moment I just use a hardcoded one:
imgPoster = new Image(getClass().getResourceAsStream("../resources/images/posters/" + 5 + ".jpg"));
In the datafile there is one column with the ID of the movie and the same number is also the picture for it. So I need to replace that "5" in the sample code with a binding or so that it actively changes the picture as soon as I click on a row in the tableview.
How do I do that?
edit:
After the first comment i did that:
imgOscars = new Image(getClass().getResourceAsStream("../resources/images/oscar/Oscar-logo.png"));
oscars = new ImageView(imgOscars);
oscars.setPreserveRatio(true);
oscars.setFitHeight(45);
but question stays
Either add a listener to the selected item property in the table (I am just guessing at the model you are using for the table):
TableView<Movie> table = ... ;
table.getSelectionModel().selectedItemProperty().addListener((obs, oldSelectedMovie, newSelectedMovie) -> {
if (newSelectedMovie == null) {
oscars.setImage(null);
} else {
// get image from new selection
Image image = new Image(getClass().getResourceAsStream("../resources/images/oscar/"+newSelectedMoviegetId()+".png"));
oscars.setImage(image);
}
});
or use a binding:
oscars.imageProperty().bind(Bindings.createObjectBinding(() -> {
if (table.getSelectionModel().getSelectedItem() == null) {
return null ;
} else {
Movie selected = table.getSelectionModel().getSelectedItem();
return new Image(getClass().getResourceAsStream("../resources/images/oscar/"+selected.getId()+".png")); ;
},
table.getSelectionModel().selectedItemProperty());

SWT Table with date chooser fields

This is an obvious question but for some reason I haven't found a solution that works. I have a table with 3 columns, the first two are dates, the third one I'm using a Spinner because I want the user to only enter numbers. I need all fields to be editable, but
the field should be editable only when it's in focus, when it's clicked on
the other fields in the same row should not be editable
when the field loses focus, it should go back to "default" mode
These are all normal things that one would expect in an editable table. For some reason I couldn't make this work in SWT. Right now what I have is:
I add a new row, all fields are "default"
I click on the row, all fields turn into editable (the date fields become combo boxes etc.)
after the row losing focus, it remains editable
This is the code that I have right now, it's based on some other code I found on the internet:
// this will happen when you click on the table
table.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Clean up any previous editor control
final TableEditor editor1 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor1.horizontalAlignment = SWT.LEFT;
editor1.grabHorizontal = true;
editor1.minimumWidth = 50;
Control oldEditor = editor1.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// Identify the selected row
TableItem item = (TableItem)e.item;
if (item == null) return;
// this is the editor for the first column
DateTime startDateTxt = new DateTime(table, SWT.BORDER | SWT.DROP_DOWN | SWT.LONG);
startDateTxt.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DateTime text = (DateTime)editor1.getEditor();
editor1.getItem().setText(0, new LocalDate(text.getYear(), text.getMonth(), text.getDay()).toString());
}
});
editor1.setEditor(startDateTxt, item, 0);
// and now comes the editor for the 2nd column
//~~~~
// Clean up any previous editor control
final TableEditor editor2 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor2.horizontalAlignment = SWT.LEFT;
editor2.grabHorizontal = true;
editor2.minimumWidth = 50;
oldEditor = editor2.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// this is the editor for the second column
DateTime endDateTxt = new DateTime(table, SWT.BORDER | SWT.DROP_DOWN | SWT.LONG);
endDateTxt.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
DateTime text = (DateTime)editor2.getEditor();
editor2.getItem().setText(1, new LocalDate(text.getYear(), text.getMonth(), text.getDay()).toString());
}
});
editor2.setEditor(endDateTxt, item, 1);
//~~~~
// Clean up any previous editor control
final TableEditor editor3 = new TableEditor(table);
// The editor must have the same size as the cell and must
// not be any smaller than 50 pixels.
editor3.horizontalAlignment = SWT.LEFT;
editor3.grabHorizontal = true;
editor3.minimumWidth = 50;
oldEditor = editor3.getEditor();
if (oldEditor != null)
oldEditor.dispose();
// this is the editor for the third column
Spinner percentTxt = createNewSpinner(table, SWT.NONE);
percentTxt.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent me) {
Spinner text = (Spinner)editor3.getEditor();
editor3.getItem().setText(2, text.getText());
}
});
editor3.setEditor(percentTxt, item, 2);
//~~~~
}
});
As you can see, when the user clicks on the table, I get the current row, and add 3 editors to the row. What I would like to do is get the selected column. I haven't found how to do this. If I get the selected column, then I would be able to create an editor just for the selected cell, and not the whole row.
I also haven't figured out how to dispose the editor after it loses focus. If the user clicks outside the table, then it has clearly happened. But what if the user just clicks on another cell? Then I would have to dispose the old editor and create a new one.
To get the selected column you can call TableItem.getBounds(columnIndex) for each column and see if the selection is within the rectangle returned.

Edit a specific cell in JTable on enter key and show the cursor

I have added a keylistner to JTable on frame.
Now on kepressed i have the code
if (ke.getKeyCode()==10)
{
int rowIndex = jTable2.getSelectedRow();
int colIndex = jTable2.getSelectedColumn();
jTable2.editCellAt(rowIndex, colIndex);
ke.consume();
this does edit the cell but the cursor is not shown till i click on it by mouse
Do not use a KeyListener!
Swing was designed to use Key Bindings (see the Swing tutorial on How to Use Key Bindings). That is you bind an Action to a KeyStroke.
By default:
The Enter key will move the cell selection to the next row
The F2 key will place a cell in edit mode
So you want to replace the default Action of the Enter key with the Action of the F2 key. This is easily done by using Key Bindings:
InputMap im = table.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
KeyStroke f2 = KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0);
im.put(enter, im.get(f2));
Also, check out Key Bindings for a list of the default bindings for all Swing components.
Try add Robot for F2 keyPressed:
if (ke.getKeyCode()==10)
{
int rowIndex = jTable2.getSelectedRow();
int colIndex = jTable2.getSelectedColumn();
jTable2.editCellAt(rowIndex, colIndex);
ke.consume();
Robot pressF2 = null;
try {
pressF2 = new Robot();
} catch (AWTException ex) {
System.err.println(ex.getMessage());
}
pressF2.keyPress(KeyEvent.VK_F2);
}
I hope this work.

Using JComboBox as a search box

Im using a JComboBox to search a query from a sql database. Here is my code.
private void srKeyTyped(java.awt.event.KeyEvent evt){
sr.removeAllItems();
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
sr.setSelectedItem(null);
sr.setPopupVisible(true);
System.out.println(sch);
}
sr = JComboBox
But when i type a letter in combobox, it adds all the items in database. I came to know that System.out.println(sch); always gives an empty string. And as soon as i type a letter, the text field of combo box becomes empty(i cant type a word with two letters). How to fix this? Thank you.
The reasons for your problems are the following:
sch is always empty is because you are calling sr.removeAllItems(); before you call String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();. This means that the contents of the JComboBox is cleared (along with the selection) before you get what is selected.
Solution: Call sr.removeAllItems();AFTER you have got the selected item.
The combo box becomes empty because you call sr.setSelectedItem(null); at the end after you have repopulated it.
Solution: If you want the entered text then sr.getEditor().setItem(scr);
Only and idea but try to enclose the contents of the method in an if statement and check if the Enter key is pressed. That way the method contents will only execute after the desired string is input and not EVERY time a key is pressed.
Use an ActionListener instead of the looking for the key press. When a combobox's selection is edited it will fire an ActionEvent when the editing is done.
When you get this part working, you should move this logic off to another thread and populate the combobox's items when it returns. Otherwise your UI will hang while the SQL query occurs.
Got the solution. This code works fine.
private void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)sr.getEditor().getEditorComponent()).getText();
String schh = "SELECT * FROM tbl WHERE name LIKE '" + sch + "%';";
search = conn.getQuery(schh);
sr.removeAllItems();
try {
while (search.next()) {
String item = search.getString("name");
sr.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
sr.setSelectedItem(null);
sr.setPopupVisible(true);
((JTextField)sr.getEditor().getEditorComponent()).setText(sch);
}
Thanks to Skepi,Kleopatra, Guillaume Polet

Categories

Resources