Why my JTable row is not selected at first click? It is selected every time after first click. What is the problem?
I need to get all the values from the row which is clicked. Here is my code. It works well from second click.
private void tblAccountInfoMouseReleased(java.awt.event.MouseEvent evt) {
try {
DefaultTableModel model = (DefaultTableModel) tblAccountInfo.getModel();
txtUserName.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 0).toString());
try {
txtPassword.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 1).toString());
} catch (NullPointerException npe) {
}
try {
txtType.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 2).toString());
} catch (NullPointerException npe) {
}
try {
txtUrl.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 3).toString());
} catch (NullPointerException npe) {
}
updateId = tblAccountInfo.getSelectedRow();
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
} catch (ArrayIndexOutOfBoundsException aiobe) {
aiobe.printStackTrace();
}
}
Related
I have one table where it shows some data from sql server and when I click it it also shows data on text fields that gets it directly from the table. But once I click one row on the table it remains clicked until the frame is closed. How can I disable it? Heres my code on click event.
int rowIndex;
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
rowIndex = jTable1.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if(model.getValueAt(rowIndex, 3).toString().equals("Mashkull "))
{
jRadioButton1_mashkull1.setSelected(true);
jRadioButton2_femer1.setSelected(false);
} else {
jRadioButton2_femer1.setSelected(true);
jRadioButton1_mashkull1.setSelected(false);
}
jTextField1_id1.setText(model.getValueAt(rowIndex, 0).toString());
jTextField1_emri1.setText(model.getValueAt(rowIndex, 1).toString());
jTextField1_mbiemri2.setText(model.getValueAt(rowIndex, 2).toString());
jTextField1_nrtel1.setText(model.getValueAt(rowIndex, 5).toString());
jTextArea1_adresa1.setText(model.getValueAt(rowIndex, 6).toString());
Date bdate;
try {
bdate= new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(rowIndex, 4).toString());
jDateChooser1_data1.setDate(bdate);
} catch (ParseException ex) {
Logger.getLogger(kontrollostudentet.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can make a call to clearSelection() right after getting the row index.
public void clearSelection()
Deselects all selected columns and rows.
The print button below displays the printer selection window but it prints nothing ...but the JTable contains data
print_button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
boolean complete = table2.print();
if (complete) {
JOptionPane.showMessageDialog(null, "Done printing");
} else {
JOptionPane.showMessageDialog(null, "printing.....");
}
} catch (PrinterException pe) {
}
}});
You need to give a size to your JTable in order to get printed:
table2.setSize(table2.getPreferredSize());
It's correct that it has data, but it needs to have a size for the priniting to work.
i got the answer
print_button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
MessageFormat header = new MessageFormat("report printing");
MessageFormat footer = new MessageFormat("page{0,number,integer}");
try {
table1.print(JTable.PrintMode.NORMAL,header,footer);
} catch (PrinterException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}});
I am trying to make a ToDoList , and I create a jButton to remove a Task from the Database ,when i check the index it always gives (-1)
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);}
update:
// set DefaultListModel
tasksListModel = new DefaultListModel();
jListTasks.setModel(tasksListModel);
Then I create this method
// to clear and fill list every time method invoked
private void fillTaskList() {
tasksListModel.clear();
try {
resultSet = pstmt.executeQuery();
while (resultSet.next()) {
// System.out.println("xxx");
tasksListModel.addElement("\"" + resultSet.getString("task_name") +
"\"" + " starts at " + resultSet.getString("start_time"));
}
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this is the ActionListener of the RemoveButton
jbtnRemoveTask.addActionListener((ActionEvent e) -> {
// to fill the list with latest values in database
sqlQuery = "SELECT * FROM tasks";
try {
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// to restore the Frame to default size as I change size during the using of application
if (ToDoFrame.this.getSize().width > 515 || ToDoFrame.this.getSize().height > 440) {
// implementation for these two methods comes at the end
decreaseHeight();
decreaseWidth();
}
// System.out.println(jListTasks.getLastVisibleIndex());
// System.out.println(jListTasks.getSelectedIndex());
// this code is always executed even there is item selected
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);
try {
// System.out.println(jListTasks.getSelectedValue());
String s = jListTasks.getSelectedValue().toString();
s = s.substring(s.length() - 5);
// System.out.println(s);
// the code for updating database
sqlUpdate = "DELETE FROM tasks WHERE start_time = ?";
pstmt = connection.prepareStatement(sqlUpdate);
pstmt.setString(1, s);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Task removed successfully!");
sqlQuery = "SELECT * FROM tasks";
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
// here are the code of decreaseWidth and decreaseHeight methods
private void decreaseWidth() {
for (int i = ToDoFrame.this.getSize().width; i > 510; i -= 10) {
ToDoFrame.this.setSize(i, ToDoFrame.this.getSize().height);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void decreaseHeight() {
for (int i = ToDoFrame.this.getSize().height; i > 435; i -= 10) {
ToDoFrame.this.setSize(ToDoFrame.this.getSize().width, i);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note: the code was working perfectly before making methods to re-size the Frame , when doing the re-sizing directly inside the ActionListener
Thanks for help
It looks like the action listener of your remove button calls the fillTaskList method before retrieving the selected index. The refill of the todo list will clear the selection in the list and the call to jListTasks.getSelectedIndex() will return -1.
I think you only need to update the todo list after removing the selected item.
another problem. I wanted to make doubleclick on JTable which open new window with form. So finally i made it this way:
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
int viewRow = table.getSelectedRow();
if(viewRow < 0)
System.out.println("LOL");
else{
final int modelRow = table.convertRowIndexToModel(viewRow);
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 2)
try {
new BookForm();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
});
It works, but not perfect. First time when i doubleclick on JTable it opens 2 windows (why not one?), next time it opens 4 windows, next another 6 windows, etc. Any ideas? Maybe i should have to use different method? Thanks for help!
Take a second to look over your code...
Each time the selection changes, you add a new MouseListener
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
int viewRow = table.getSelectedRow();
if(viewRow < 0)
System.out.println("LOL");
else{
// You add a new mouse listener...
final int modelRow = table.convertRowIndexToModel(viewRow);
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 2)
try {
new BookForm();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}
}
});
So, when you "finally" double click a row, you will have 1-n MouseListeners registered against the table...
You could just get rid of the selection listener and simple add the MouseListener directly to the table...
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 2)
int selectedRow = table.getSelectedRow();
if (selectedRow > -1) {
int modelRow = table.convertRowIndexToModel(selectedRow);
try {
new BookForm();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
Also take a look at The Use of Multiple JFrames: Good or Bad Practice? before you bomb bard your user with lots of new windows...
I'm struggling with update my item in JComboBox. When I load item from a file, the combobox display properly, however when I tried to add or remove item from combobox item, the combobox doesn't update automatically, it still remain the same item instead. Here is my code
This is where I load the combobox item
ObjectInputStream input;
try {
// TODO add your handling code here:
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
diary = (Diary)input.readObject();
jTextArea3.setText(diary.getUnitCollection().toString());
input.close();
//Load Unit Item
for (Unit u: diary.getUnitCollection()){
jComboBox8.addItem(u.getUnitName());
jComboBox1.addItem(u.getUnitName());
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
This is button to remove item
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
for (int i = 0; i < diary.getUnitCollection().size(); i++){
if (jComboBox8.getSelectedItem().equals(diary.getUnitCollection().get(i).getUnitName())){
diary.getUnitCollection().remove(diary.getUnitCollection().get(i));
jTextArea3.setText("The Unit " + jComboBox8.getSelectedItem()+ " has been removed successfully");
}
}
}
edit: just fix style (code block)
You need to add and remove content via a model, check out http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html