I want show customer details from a MySQL database in a JTable, but I don't see any result in my panel when I click the "show" button.
This is the method to add the table to the JScrollPane:
void addTable()
{
for(int i=0 ; i<myTableModel.getColumnCount();i++)
{
myTableModel.getColumnName(i);
}
showCustomers();
table.setModel(myTableModel);//mytablemodel is a object from MyTableModel Class
scrollPane.add(table); //was on another part of program but i edit it for helping to answers
panel_show.add(scrollPane);
}
And here is MyTableClass, implementing TableModel, with a new method, addCustomer. addCustomer will add a Customer to the CustomerList. I am trying ArrayList for first time to show Customer data but it doesn't work.
Also, columnName will make the table headers with the column names from the database.
public class MyTableModel implements TableModel
{
private ArrayList<Customer> customerList;
private String[] columnName =
{"id", "name", "family", "idc", "age", "sex", "balance", "tel", "haveFamily", "population"};
#Override
public int getRowCount()
{
//return customerList.size();
return 1;
}
#Override
public int getColumnCount()
{
return 10;
}
#Override
public String getColumnName(int columnIndex)
{
return columnName[columnIndex];
}
#Override
public Class<?> getColumnClass(int columnIndex)
{
if(columnIndex == 0)
return Integer.class;
return String.class;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return false;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if(columnIndex == 0)
return customerList.get(rowIndex).getId();
else if(columnIndex == 1)
return customerList.get(rowIndex).getName();
else if(columnIndex == 2)
return customerList.get(rowIndex).getFamily();
else if(columnIndex == 3)
return customerList.get(rowIndex).getIdc();
else if(columnIndex == 4)
return customerList.get(rowIndex).getDate();
else if(columnIndex == 5)
return customerList.get(rowIndex).getSex();
else if(columnIndex == 6)
return customerList.get(rowIndex).getBalance();
else if(columnIndex == 7)
return customerList.get(rowIndex).getTel();
else if(columnIndex == 8)
return customerList.get(rowIndex).isHaveFamily();
else if(columnIndex == 9)
return customerList.get(rowIndex).getPopulation();
else
return null;
}
public void addCustomer(Customer customer)
{
CustomerManager customerManager = new CustomerManager();
customerManager.addCustomer(customer);
customerList.add(customer);
}
The showCustomer method will be open a database connection and create a TableModel with customers, which is then used for the table on my panel.
public void showCustomers()
{
Connection conn = null;
try
{
//String user = "root";
// String pass = null;
//String url = "jdbc:mysql://localhost/estate";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/estate", "root", null);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * from customer");
//int columnCount = rsmd.getColumnCount();
while (rs.next())
{
myTableModel.addCustomer(new Customer(1,"david","schmidt","0025674433","31","Male","200000","4545552132","true","2");
}//Original Form --> Customer({"id","name","family","idc","age",
// "sex","balance","tel","haveFamily","population"});
}
In MyTableModel I make an addCustomer method and fill the customer data using a ResultSet. Is it needed?
My question: How can I show my Customers using a JTable?
After some fiddling I now also have a problem with myTableModel.addCustomer(rs.getInt(), ...). The error I am getting is this:
Error in addCustomer,Duplicate entry '0' for KEY PRIMARY
However, I don't have a customer with an ID of 0.
When displaying a JTable you first add the table to a scroll pane and then you add the scroll pane to a panel.
When adding a component to a visible GUI you need to make sure the layout manager has been invoked so that the component has a size and location.
So the basic code would be:
table.setModel(...);
JScrollPane scrollPane = new JScrollPane( table );
panel.add( scrollPane );
panel.revalidate();
panel.repaint();
The other approach is the create an empty table and add the scroll pane to the GUI when you first create the GUI. Then all the code you need is:
table.setModel(...);
Edit:
You question is about displaying a table in a panel, when you click a button. So that is ALL the SSCCE should do. Where the data comes from is irrelevant, so posting code dealing with a database is completely unnecessary, because we can't execute the code. A custom TableModel is irrelevant to the real question.
Here is a simple SSCCE that uses my second suggestion of updating an existing table with a new model. Every time you click the button the number of columns changes. This simulates getting new data from somewhere.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class RefreshSSCCE extends JPanel
{
private JTable table = new JTable();
private int columns = 3;
public RefreshSSCCE()
{
setLayout( new BorderLayout() );
JButton refresh = new JButton( "Refresh Data" );
add(refresh, BorderLayout.NORTH);
refresh.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
refreshData();
}
});
add(new JScrollPane(table), BorderLayout.CENTER);
}
private void refreshData()
{
DefaultTableModel model = new DefaultTableModel(5, columns++);
table.setModel( model );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Refresh SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new RefreshSSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
See how easy that code is to understand? The code is complete and in one class. It can easily be copied and pasted so others can test the code.
When you simplify the problem then solution is usually much easier. That is why you take the time to create a SSCCE. Even if the SSCCE doesn't work the way you want, we only have a couple of lines of code to look at to understand what you are attempting to do. There is no need to complicate the question with SQL code.
Once you get the simple code working you then modify the refreshData method to get real data. That is what I mean by hardcoding data. There is no need for a dynamic query of the database to demonstrate your problem of displaying a table in a panel.
Related
I have a JTable. User will enter an ID in a particular column and press TAB. I need to add event on that column to fetch value from DB and populate the rest of the columns of that row and create a new row for the next entry.
I am new to Swing and its difficult to find what is the best way to do it as i can see examples which were written in 2010 or so. Not sure if thats relevant still.
What I don't know:
adding event handler to a particular column's cell in table.
add next row after populating the data.
You can use a TableModelListener for this. When user change ID column value, tableChanged() is invoked. Then the relevant data is fetched from the DB and set in the row. And a new row is added as well. Try below example.
(For demonstration purpose I have used a mock database in this example. It only gives rows for IDs "111" and "222".)
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
import java.util.Vector;
public class TableDataChange
{
public static void main(String[] args)
{
DefaultTableModel tableModel = new DefaultTableModel(
new Object[][] {{"", "", ""}},
new Object[] {"ID", "Column 2", "Column 3"});
tableModel.addTableModelListener(new TableModelListener()
{
#Override
public void tableChanged(TableModelEvent e)
{
String id = (String) tableModel.getValueAt(e.getFirstRow(), 0);
if (id != null)
{
Vector row = Database.loadRowForId(id);
tableModel.getDataVector().set(e.getFirstRow(), row);
tableModel.addRow(new Vector());
}
}
});
JTable table = new JTable(tableModel);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(table));
f.setBounds(300, 200, 400, 300);
f.setVisible(true);
}
}
// Mock database
class Database
{
static Vector loadRowForId(String id)
{
Vector row = new Vector();
if (id.equals("111"))
{
row.add("111");
row.add("aaa");
row.add("bbb");
}
else if (id.equals("222"))
{
row.add("222");
row.add("ppp");
row.add("qqq");
}
return row;
}
}
You can try something like this,
//Add Key Listener
table.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event) {
if (event.getKeyChar() == KeyEvent.VK_TAB) {
int selectedColumn = table.getSelectedColumn();
//Now you can search records related to ID and populate the table
}
}
});
In a previous question (Convert modelRowIndex to viewRowIndex for sorted JTable) I indicated that I was trying to create a "simple" JTable that used a TableModel to tie an ArrayList to a JTable using a TableModel. My goal was - and still is - to retain all of java's built-in JTable functionality that allows cell editing, row sorting, and column rearranging. Thanks to your help, that functionality now works.
I'm now trying to add the ability to Insert and Delete table rows. The (updated) example I provide here works ... EXCEPT ... under a certain sequence of operations, an "IndexOutOfBoundsException" is thrown. Here's my code:
package tableexample;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public final class TableExample extends JFrame {
List<REItem> REList;
JTable tblREList;
JButton btnAddInsertRE, btnDeleteRE;
JScrollPane spMain;
JFrame frame;
Container pane;
public TableExample() {
// create and populate the ArrayList
REList = new ArrayList<>();
REList.add(new REItem("Template1", "Comment1"));
REList.add(new REItem("Template2", "Comment2"));
RETableModel retm = new RETableModel(REList); // Connect the List to the TableModel
// create GUI components
frame = new JFrame ("Table Example");
btnAddInsertRE = new JButton("Add/Insert");
btnDeleteRE = new JButton("Delete");
tblREList = new JTable(retm);
tblREList.setAutoCreateRowSorter(true);
spMain = new JScrollPane(tblREList);
// add button ActionListeners
btnAddInsertRE.addActionListener((ActionEvent evt) -> { btnAddInsertREActionPerformed(evt); });
btnDeleteRE.addActionListener((ActionEvent evt) -> { btnDeleteREActionPerformed(evt); });
// place GUI components and make the GUI visible
pane = frame.getContentPane();
pane.setLayout (null);
pane.add(btnAddInsertRE);
pane.add(btnDeleteRE);
pane.add(spMain);
btnAddInsertRE.setBounds (10, 10, 100, 25);
btnDeleteRE.setBounds (120, 10, 100, 25);
spMain.setBounds (10, 45, spMain.getPreferredSize().width, spMain.getPreferredSize().height);
frame.setSize(spMain.getWidth() + 40, spMain.getHeight() + 95);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} // end TableExample constructor
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TableExample notUsed = new TableExample();
});
} //end main
private void btnAddInsertREActionPerformed(ActionEvent evt) {
// Add a FileSelection object to the ArrayList
int r = tblREList.getSelectedRow(); // get row selection, if any
if (r < 0) { // no row selected
REList.add(new REItem("NewTemplate", "NewComment")); // append new item to end
r = REList.size()-1; // get index to new item
} else { // else no row selected
REList.add(r, new REItem("NewTemplate", "NewComment")); // insert above selected row
} // row selected or not
spMain.setViewportView(tblREList); // repaint the updated table
tblREList.getSelectionModel().setSelectionInterval(r, r); // select the new row
}
private void btnDeleteREActionPerformed(ActionEvent evt) {
int[] selRows = tblREList.getSelectedRows(); // see if any rows are selected
if (selRows.length>0) { // at least one row is selected
for (int r=selRows.length-1; r>=0; r--) { // delete each row, from the bottom up,
REList.remove(r); // so that indexes are correct and
} // don't change with each delete
tblREList.clearSelection(); // clear the row selection data
spMain.setViewportView(tblREList); // repaint the updated table
} else { // else no row(s) selected
JOptionPane.showMessageDialog(null, "Must select at least one item to delete");
} // no row selected
} // end btnDeleteREActionPerformed
public final class REItem {
String template;
String comment;
public REItem(String tmp, String cmt) {
this.template = tmp;
this.comment = cmt;
}
} // end class REItem
public class RETableModel extends AbstractTableModel {
private List<REItem> reList = new ArrayList();
private final String[] columnNames = { "Template", "Comment" };
public RETableModel(List<REItem> list){
this.reList = list;
}
#Override
public String getColumnName(int column){
return columnNames[column];
}
#Override
public int getRowCount() {
return reList.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public Object getValueAt(int row, int column) {
switch (column) {
case 0: return reList.get(row).template;
case 1: return reList.get(row).comment;
}
return null; // default case
}
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
#Override
public Class<?> getColumnClass(int column){
switch (column){
case 0: return String.class;
case 1: return String.class;
}
return null; // default case
}
#Override
public void setValueAt(Object value, int row, int column) {
switch (column) {
case 0: reList.get(row).template = value.toString(); break;
case 1: reList.get(row).comment = value.toString(); break;
}
// uncommenting the below often causes IndexOutOfBoundsException: Invalid range exception
fireTableCellUpdated(row, column);
} // end setValueAt
} // end RETableModel
} // end class TableExample
The problem can be reproduced as follows: Run the above example, click the "Add/Insert" button to append a new row to the table, click either column header to re-sort the table, then click the "Delete" button: An "IndexOutOfBoundsException" is thrown, indicating that the "row" index specified by the TableModel's getValueAt method is flawed.
I assume the issue is related to the need for my TableModel.getValueAt (and maybe .setValueAt ???) method(s) to convert between TableModel column indexes and View column indexes but, for the life of me, I can't figure out how or where to make the conversion. Morevover, this question (Convert modelRowIndex to viewRowIndex for sorted JTable) indicates that a conversion between TableModel and View row-indexes is needed, AND that table re-sorting MUST occur before the index conversion is done.
Try as I might, I cannot figure out how to make the conversion and/or how to make sure that conversion happens AFTER the table is updated and re-sorted. Do I need a Listener? If so, what should it look like?
Can you provide some clarification and help?
First of all, variable names should NOT start with an upper case character. This is a Java convention and it messes with the formatting of the code you post making your code hard to read. Fix your variables and follow Java conventions.
The ArrayList should only be used to initially add data to the model.
After that updates should be done to the TableModel, not the ArrayList. So you need to add methods to your TableModel like addREItem(...) and removeREItem(...).
See Row Table Model for a step-by-step example of how to build a custom TableModel for a given object, including how the code the add???(...) and remove???(...) method.
And if you want to remove selected rows from the table then check out: How to delete multiple rows from JTable , database at a time for a working examples that shows how this can be done using the remove???(...) method.
So I am creating a project which has three columns; one is a check box column the second one is string (words form a neo4j database) and the third for progress bars.
All the columns are displayed and work fine but the progress bar column is invisible as it seems. Here is some code:
//CONSTRUCTOR
public BiogramTableJSedit2Jan9()
{
//*************************************************
//* SETTING UP THE FORM *
//*************************************************
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(200,200,800,300);
setTitle("Netword Data Table");
getContentPane().setLayout(null);
//*************************************************
//********************************************
//CREATING TABLE BLOCK *
//********************************************
//ADD SCROLLPANE
JScrollPane scroll=new JScrollPane();
scroll.setBounds(70,80,600,200);
getContentPane().add(scroll);
//THE TABLE
final JTable table=new JTable();
scroll.setViewportView(table);
//THE MODEL OF THE TABLE
DefaultTableModel model=new DefaultTableModel()
{
//****************************************
//* SETTING TABLE COLUMNS BLOCK *
//****************************************
public Class<?> getColumnClass(int column)
{
switch(column)
{
case 0: // |This is the first column
return Boolean.class; // |First column is set to Boolean as it will contain check boxes
case 1: // |This is the second column
return String.class; // |Second column set to String as it will contain strings
case 2:
return JProgressBar.class; // |This is for the progress bar column (IN PROGRESS - NOT DISPLAYED YET...)
default:
return String.class; // |The table is set to String as default
}
}
};
//Create and run the query in the table
neoQuery= Q1();
resultVariable = session.run(neoQuery.get());
//ASSIGN THE MODEL TO TABLE
table.setModel(model);
model.addColumn("Select"); // |Column for check boxes
model.addColumn("Bigrams"); // |Column for Bigrams
table.getColumn("Status").setCellRenderer(new ProgressCellRender());
//**********************************************
ProgressWorker worker = new ProgressWorker(model); //HAVE AN ERROR HERE
worker.execute();
This is the progress renderer class:
//a table cell renderer that displays a JProgressBar
public class ProgressCellRender extends JProgressBar implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
int progress = 0;
if (value instanceof Float) {
progress = Math.round(((Float) value) * 100f);
} else if (value instanceof Integer) {
progress = (int) value;
}
setValue(progress);
return this;
}
}
Now you can see that I am using getColumn in order to display this column but when I run it you can see the first and second but not the progress bar column. I want it to look similar to this:
I also has a progress worker class that is not fully implemented.
private static class ProgressWorker extends SwingWorker<Void, Integer>
{ //Swing worker class for updating the progress bar
private BiogramTableJSedit2Jan9 model;
private final JProgressBar progress; //declaration for progress bar
public ProgressWorker(JProgressBar model)
{
this.progress = model;
}
#Override
protected Void doInBackground() throws Exception {
return null;
}
I would appreciate if anyone can explain to me why the thirst column is not being displayed. Thanks for any replies in advance.
Because your posted code was not self-contained I set up a minimal test together
with your already posted ProgressCellRender class.
The important bugfix is in method getColumnClass of the DefaultTableModel.
It needs to return Integer.class or Float.class because only those can be
handled by your ProgressCellRender.
And of course, the actual data in that column need to be Integer or Float.
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(Main::initGUI);
}
private static void initGUI() {
JFrame frame = new JFrame("TableModel JProgressBar Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scroll = new JScrollPane();
frame.getContentPane().add(scroll);
final JTable table = new JTable();
scroll.setViewportView(table);
DefaultTableModel model = new DefaultTableModel() {
public Class<?> getColumnClass(int column) {
switch (column) {
case 0:
return Boolean.class;
case 1:
return String.class;
case 2:
return Integer.class; // !!!!
default:
return String.class;
}
}
};
table.setModel(model);
model.addColumn("Active");
model.addColumn("Name");
model.addColumn("Progress");
table.getColumn("Progress").setCellRenderer(new ProgressCellRender());
model.addRow(new Object[] { true, "aaaa", 14 });
model.addRow(new Object[] { false, "bbbbbbbb", 0 });
model.addRow(new Object[] { true, "ccccc", 2 });
frame.pack();
frame.setVisible(true);
}
}
Then the JProgressBars are rendered correctly in the table:
In your ProgessCellRender you may want to add setStringPainted(true); to get the percentage also rendered as text.
How can I prevent strings in a JTable and allow and show only numbers?
like for example I press "a" on my keyboard I won't not even that "a" will be displayed in the JTable cell. literally nothing should happen unless a user types in a number. so how can I prevent even not showing "a" ?
I had a similar issue some time ago and solved by validating with an KeyListener. This is a dirty way of doing it, but it works. The only weakness is if you're trying to edit a lot of cells quickly if you're a fast writer. Anyhow, here's the code that worked for me. I've added some commentary, but in short; we're overriding the normal validation and check with a TextField KeyListener if the given key is the one we allow in the TextField. If we allow the key, we enable TextField editing, if not, we turn it off to prevent the character being printed in the TextField. I hope this helps you.
UPDATE 1:
adding a celleditor on the TestField to prevent premature data insertion.
public class TableValidation extends JFrame
{
public static void main(String args[])
{
TableValidation x = new TableValidation();
x.setVisible(true);
}
JPanel topPanel;
JTable table = new JTable();
JScrollPane scrollPane;
String[] columnNames;
String[][] dataValues;
public TableValidation()
{
this.setTitle("JTable Cell Validation");
this.setDefaultCloseOperation (EXIT_ON_CLOSE);
this.setSize(300,112);
// make our panel to tin the table to
topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
this.getContentPane().add(topPanel);
// set some initial data for the table
columnNames = new String[] {"Anything" ,"Numbers only"};
dataValues = new String[][] { {"h4x0r","1337"} };
table.setRowHeight(50);
table.setModel( new CustomTableModel(dataValues, columnNames) );
TableColumn tableColumn = table.getColumnModel().getColumn(1); // apply our validation to the 2nd column
JTextField textfield = new JTextField(); // the textbox to which we test our validation
// setup our validation system. were passing the textfield as out celleditor source
tableColumn.setCellEditor(new MyCellEditor(textfield));
table.setCellSelectionEnabled(true);
scrollPane = new JScrollPane(table);
topPanel.add(scrollPane,BorderLayout.CENTER);
textfield.addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent e)
{
// check what keys can pass our test
if (textfield.isFocusOwner())
if (e.getKeyChar() != KeyEvent.VK_BACK_SPACE) // we allow backspace, obviously
if (!Character.isDigit(e.getKeyChar())) // if key is not a digit.. cancel editing
{
// when it detects an invalid input, set editable to false. this prevents the input to register
textfield.setEditable(false);
textfield.setBackground(Color.WHITE);
return;
}
textfield.setEditable(true);
}
});
}
}
class MyCellEditor extends AbstractCellEditor implements TableCellEditor
{
private static final long serialVersionUID = 1L;
private JTextField textField;
public MyCellEditor(JTextField textField)
{
this.textField=textField;
}
#Override
public boolean isCellEditable(EventObject e)
{
if (super.isCellEditable(e)) {
if (e instanceof MouseEvent) {
MouseEvent me = (MouseEvent) e;
return me.getClickCount() >= 2;
}
if (e instanceof KeyEvent) {
KeyEvent ke = (KeyEvent) e;
return ke.getKeyCode() == KeyEvent.VK_F2;
}
}
return false;
}
#Override
public Object getCellEditorValue()
{
return this.textField.getText();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
this.textField.setFont(table.getFont());
this.textField.setText(value.toString());
return this.textField;
}
}
class CustomTableModel extends DefaultTableModel
{
CustomTableModel(String[][] data,String[] names)
{
super(data, names);
}
// we always pass true in our tablemodel so we can validate somewhere else
public boolean isCellEditable(int row,int cols)
{
return true;
}
}
This question already has answers here:
How to make a JTable non-editable
(7 answers)
Closed 9 years ago.
I have a table which is clickable but when I double click, instead of doing what it is told, it goes editing mode. I have tried isCellEditable() method with no success. Maybe I am doing something wrong?
Here is the code:
public AllResultsFromDB(GUI x) {
final Vector columnNames = new Vector();
final Vector data = new Vector();
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metad.getColumnName(i));
}
// This loop gets the data inside the rows
while (rset.next()) {
final Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rset.getObject(i));
}
data.addElement(row);
//data.addElement(b);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
final JTable table = new JTable(data, columnNames) {
public boolean isCellEditable() {
return false;
}
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object obj = getValueAt(row, column);
if (obj != null) {
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
table.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseReleased(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseEntered(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseExited(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2){
System.out.println(table.getSelectedRow());
}
}
});
The method isCellEditable that you tried to override has a different signature which is:
public boolean isCellEditable(int row, int column)
How could you specify which specific cell otherwise? Next time adding an #Override annotation should help spotting this.
In any case this is not the correct way to make a JTable non-editable. The correct way is to provide a custom AbstractTableModel which returns false with its isCellEditable method. The JTable shouldn't decide if a cell is editable, it's duty of the model to decide it: indeed the isCellEditable method of JTable just asks to its model if the cell is editable. The JTable shows the content, nothing more, it's the model that decides and contains the data.
Since you seem to use just basic features of a JTable you don't need to roll your own table model, a DefaultTableModel will work for you, and you can overrite its isCellEditable method.
You're not that far off.
The actual method isCellEditable takes two parameters, so your method isn't actually overriding anything.
See: http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableModel.html#isCellEditable%28int,%20int%29
for the correct method.