JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(NewJFrame1.this);
if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if(len > 4){
ext = filename.substring(len-4, len);
}
if(ext.equals(".xls")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".xls";
}
toExcel(jTable1, new File(file));
}
this is how i save my table to excel it works fine but i want to import these datas after i restart my program can someone help me about this ?
You can use Apache POI to export your JTable Data.
See how to do it here, in this thread:
apache poi: saving jtable to a file
Edit
I didn't read your question, if you're trying to IMPORT data, try these methods:
http://www.zfqjava.com/article/How-to-import-excel-into-JTabel.html
//Download and insert jxl-1.0.jar file
public class excelTojTable extends JFrame {
static JTable table;
static JScrollPane scroll;
// header is Vector contains table Column
static Vector headers = new Vector();
// Model is used to construct JTable
static DefaultTableModel model = null;
// data is Vector contains Data from Excel File
static Vector data = new Vector();
static JButton jbClick;
static JFileChooser jChooser;
static int tableWidth = 0; // set the tableWidth
static int tableHeight = 0; // set the tableHeight
public excelTojTable() {
super("Import Excel To JTable");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
jChooser = new JFileChooser();
jbClick = new JButton("Select Excel File");
buttonPanel.add(jbClick, BorderLayout.CENTER);
// Show Button Click Event
jbClick.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
jChooser.showOpenDialog(null);
File file = jChooser.getSelectedFile();
if (!file.getName().endsWith("xls")) {
JOptionPane.showMessageDialog(null,
"Please select only Excel file.",
"Error", JOptionPane.ERROR_MESSAGE);
} else {
fillData(file);
model = new DefaultTableModel(data,
headers);
tableWidth = model.getColumnCount()
* 150;
tableHeight = model.getRowCount()
* 25;
table.setPreferredSize(new Dimension(
tableWidth, tableHeight));
table.setModel(model);
}
}
});
table = new JTable();
table.setAutoCreateRowSorter(true);
model = new DefaultTableModel(data, headers);
table.setModel(model);
table.setBackground(Color.pink);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setRowHeight(25);
table.setRowMargin(4);
tableWidth = model.getColumnCount() * 150;
tableHeight = model.getRowCount() * 25;
table.setPreferredSize(new Dimension(
tableWidth, tableHeight));
scroll = new JScrollPane(table);
scroll.setBackground(Color.pink);
scroll.setPreferredSize(new Dimension(300, 300));
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
getContentPane().add(buttonPanel,
BorderLayout.NORTH);
getContentPane().add(scroll,
BorderLayout.CENTER);
setSize(600, 600);
setResizable(true);
setVisible(true);
}
/**
* Fill JTable with Excel file data.
*
* #param file file :contains xls file to display in jTable
*/
void fillData(File file) {
Workbook workbook = null;
try {
try {
workbook = Workbook.getWorkbook(file);
} catch (IOException ex) {
Logger.getLogger(
excelTojTable.class.
getName()).log(Level.SEVERE,
null, ex);
}
Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell1 = sheet.getCell(i, 0);
headers.add(cell1.getContents());
}
data.clear();
for (int j = 1; j < sheet.getRows(); j++) {
Vector d = new Vector();
for (int i = 0; i < sheet.getColumns(); i++) {
Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
}
d.add("\n");
data.add(d);
}
} catch (BiffException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new excelTojTable();
}
}
try {
jxl.Workbook workbook = jxl.Workbook.getWorkbook(file);
jxl.Sheet sheet = workbook.getSheet(0);
headers.clear();
for (int i = 0; i < sheet.getColumns(); i++) {
jxl.Cell cell1 = sheet.getCell(i, 0);
headers.add(cell1.getContents());
}
data.clear();
for (int j = 1; j < sheet.getRows(); j++) {
Vector d = new Vector();
for (int i = 0; i < sheet.getColumns(); i++) {
jxl.Cell cell = sheet.getCell(i, j);
d.add(cell.getContents());
}
d.add("\n");
data.add(d);
}
}
catch (Exception e) {
e.printStackTrace();
}
this is how i solved my problem i hope it helps someone else
Related
i have a large excel file containing 600.000 rows , i used XSSFWorkbook to upload the excel file at a Jtable in my GUI but it takes about 15 minutes to be done in eclipse and once i export my project to a jar file i can't do it even in the 15 minutes . Any help please ?
Here is the method , that i found in internet to upload my excel file .
void fillData(File file) {
int index = -1;
XSSFWorkbook workbook = null;
try {
try {
String f = file.getPath();
File file1 = new File(f);
OPCPackage opcPackage = OPCPackage.open(file1);
workbook = new XSSFWorkbook(opcPackage);
} catch (IOException ex) {
Logger.getLogger(ProjectApp3.class.getName()).log(Level.SEVERE, null, ex);
}
String[] strs = new String[workbook.getNumberOfSheets()];
//get all sheet names from selected workbook
for (int i = 0; i < strs.length; i++) {
strs[i] = workbook.getSheetName(i);
}
JFrame frame = new JFrame("Input Dialog");
//select sheet
String selectedsheet = (String) JOptionPane.showInputDialog(
frame, "Which worksheet you want to import ?", "Select Worksheet",
JOptionPane.QUESTION_MESSAGE, null, strs, strs[0]);
if (selectedsheet != null) {
for (int i = 0; i < strs.length; i++) {
if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
index = i;
}
XSSFSheet sheet = workbook.getSheetAt(index);
XSSFRow row = sheet.getRow(0);
//import headers data
headers.clear();
for (int i = 0; i < row.getLastCellNum(); i++) {
XSSFCell cell1 = row.getCell(i);
headers.add(cell1.toString());
}
//import data
data1.clear();
for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
Vector d = new Vector();
row = sheet.getRow(j);
int noofrows = row.getLastCellNum();
for (int i = 0; i < noofrows; i++) { //To handle empty excel cells
XSSFCell cell = row.getCell(i,
org.apache.poi.ss.usermodel.Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
d.add(cell.toString());
}
d.add("\n");
data1.add(d);
}
} else {
return;
}
} catch (Exception e) {
e.printStackTrace();
}
}
I think the basic problem is that you're trying to give. your Jtable all the data at startup. This is going to be deeply problematic. You may want to write a custom subclass from AbstractTableModel. See the docs for Jtable that includes this:
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return 10; }
public int getRowCount() { return 10;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
JTable table = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(table);
You can implement those three methods based on the info that POI gives you. But do lazy loading of the data, most especially for getValueAt(). Keep the spreadsheet file open and grab the data only when the user scrolls to view it.
[![enter image description here][1]][1]I'm having a problem populating a JTable from an excel file. Here is the operation, I will search, lets say "Line 1", there are 2 cells matching this value, if there is a match, I would like to pull the row and insert it into my JTable. I was able to get this working, however, this only creates one row for the first matching value, when i click on search button again, it will replace the row, with a new row, if there was more than 1 match.
I would the jtable to add both rows in the same table, rather one by one. I attached what I have so far.
Thank You in advanced.
try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(LinNum_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
DefaultTableModel model = new DefaultTableModel();
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
model.addColumn("ID", new Object[] { val_0 });
model.addColumn("Date", new Object[] { val_1 });
model.addColumn("Auditor Name", new Object[] { val_2 });
model.addColumn("Line #", new Object[] { val_3 });
table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
I was able to get this working, however, this only creates one row for the first matching value,
That is because in your "looping code" you create a new JTable each time.
Instead you want to create the table once and add data to your TableModel inside the loop. So the structure of your code should be something like:
String[] columnNames = { "Id", "Date", ... };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
for (...)
{
...
if (matched row found)
{
...
Object[] row = { val_0, val_1, ...};
model.addRow( row );
}
JTable table = new JTable( model );
...
With camickr's help I got this to work. Here is the final code.
try {
FileInputStream fis = new FileInputStream(
new File("S:\\Tester Support\\0LineTester Database\\Audit\\LASAudit.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
String[] columnNames = {"Id","Date","Auditor Name","Line Number"};
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setVisible(true);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 278, 670, 303);
contentPane.add(scrollPane);
scrollPane.setViewportView(table);
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(Spec_Text.getText())) {
int rowNum = row.getRowNum();
Row r = sheet.getRow(rowNum);
int col_0 = 0;
String val_0 = r.getCell(col_0).getStringCellValue();
int col_1 = 1;
String val_1 = r.getCell(col_1).getStringCellValue();
int col_2 = 2;
String val_2 = r.getCell(col_2).getStringCellValue();
int col_3 = 3;
String val_3 = r.getCell(col_3).getStringCellValue();
Object[] ROWS = { val_0, val_1, val_2,val_3};
model.addRow( ROWS );
}
}
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
New here so please be kind. I've spent a few hours trawling through posts trying to find an answer but no such luck.
I have an excel file that I import into a JTable and can then edit. Add columns, rows etc.
When I click the button to add a column or row they appear on the JTable as expected. However when I click the save button to save the file it hasn't added the new columns or rows to the Excel file.
I thought my save wasn't working correctly, but if I edit one of the two columns I already have saved in the Excel file the changes are saved to the Excel file so I am confused as to why I can edit the existing data in the file but any new rows or columns are not saved.
My export to excel is:
public void toExcel()
{
try
{
FileInputStream fsIP = new FileInputStream(new File("Recipes.xls"));
HSSFWorkbook fWorkbook = new HSSFWorkbook(fsIP);
HSSFSheet fSheet = fWorkbook.getSheet("RECIPES");
HSSFFont sheetTitleFont = fWorkbook.createFont();
HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
TableColumnModel tcm = tables.getColumnModel();
HSSFRow fRow = fSheet.createRow((short) 0);
for(int j = 0; j < tcm.getColumnCount(); j++)
{
HSSFCell cell = fRow.createCell((int) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
}
for (int i = 0, row = 1; i < models.getRowCount(); i++, row++)
{
HSSFRow fRow1 = fSheet.createRow((short) row);
for (int j = 0; j < models.getColumnCount(); j++)
{
HSSFCell cell = fRow1.createCell((int) j);
cell.setCellValue(models.getValueAt(i, j).toString());
cell.setCellStyle(cellStyle);
}
}
FileOutputStream output_file = new FileOutputStream(new File("Recipes.xls"));
BufferedOutputStream bos = new BufferedOutputStream(output_file);
fWorkbook.write(output_file);
fWorkbook.close();
bos.close();
output_file.close();
}
catch(Exception e)
{
}
JOptionPane.showMessageDialog(
null, "Changes Saved",
"Confirmation",
JOptionPane.INFORMATION_MESSAGE);
}
My method for adding a column is as follows:
public void addNewRecipe()
{
models.addColumn(JOptionPane.showInputDialog("Enter A Description for Recipe"));
}
Thanks.
EDIT
Here is code for calling toExcel
saveButton.addActionListener(new ActionListener()
{
#Override public void actionPerformed(ActionEvent arg0)
{
{
models = new DefaultTableModel(datas, headers);
tableWidth = models.getColumnCount() * 150;
tableHeight = models.getRowCount() * 50;
tables.setPreferredSize(new Dimension( tableWidth, tableHeight));
tables.setModel(models);
tables.setRowHeight(50);
toExcel();
}
}
});
I've made a GUI in Java that connects with a MySQL server and inserts,deletes,updates data. I have a section on this GUI that you can write in a text area a MySQL query and the result is displayed on a Jtable. Everything works fine! I can print the data from the JTable or save them to a text file!
Now, I want to add another feature: When I double click on a specific cell, I would like to change the data of the JTable, and I want this data to be updated in the MySQL table with the click of a button as well.
I've searched all over the internet, but I can't find a good example or a good solution. The JTable I have is dynamic; that means that what ever query is inserted the data will be displayed with the quired column names and data
Here is the code:
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
data_connector getdata1 = new data_connector();
host = getdata1.getHost();
username = getdata1.getUsername();
password1 = getdata1.getPassword();
mysql_command = getdata1.getMysql_command();
command_name = getdata1.getCommand_name();
setTitle(command_name);
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://"+host+":3306/xxxxx";
String userid = username;
String password = password1;
String sql = mysql_command;
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
columnNames.add(md.getColumnName(i));
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
row.add(rs.getObject(i));
data.add(row);
}
}
catch (SQLException e)
{
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(null, e.getMessage());
mysql_fail_flag = 1;
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
subVector.add(subArray.get(j));
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
contentPane.setLayout(null);
// Create table with database data
table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
return o.getClass();
}
return Object.class;
}
};
// table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(5, 5, xframeWidth-20, yframeHeight-70);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(5, 856, 1574, 1);
getContentPane().add(buttonPanel);
buttonPanel.setLayout(null);
In the form you actually create your JTable, I don't think this is easy. What you want to do is subclassing AbstractTableModel, and overwrite the setValueAt() method. You subclass could look like this:
class MyModel extends AbstractTableModel
{
private ResultSet result;
private ResultSetMetaData metadata;
public MyModel (ResultSet rs)
{
super();
result = rs; // mustn't be null, maybe check and throw NPE
metadata = result.getMetaData();
}
public int getRowCount ()
{
result.last();
return result.getRow(); // See http://stackoverflow.com/questions/8292256/get-number-of-rows-returned-by-resultset-in-java
}
public int getColumnCount ()
{
return metadata.getColumnCount();
}
public Object getValueAt (int row, int col)
{
result.absolute(row);
return result.getString(col);
}
public String getColumnName (int col)
{
return metadata.getColumnName(col);
}
public void setValueAt (Object value, int row, int col)
{
result.absolute(row);
result.updateObject(col, value);
}
}
I haven't tested it, but your code must look like this. Note that you mustn't close the Statement, Connection or the ResultSet (or create a new ResultSet cause some db drivers like MySQL destroy the old one) to prevent any Exceptions.
OK!!! i managed to update every cell separately by just editing the cell and then pressing enter!
This works only for 1 table but its ok for my project! Here is the code...
private class RowColumnListSelectionListener implements ListSelectionListener {
public void valueChanged(ListSelectionEvent e) {
rowIndexStart = table.getSelectedRow();
rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
colIndexStart = table.getSelectedColumn();
colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
for ( i = rowIndexStart; i <= rowIndexEnd; i++) {
for ( j = colIndexStart; j <= colIndexEnd; j++) {
Object cell_value = table.getValueAt(i,j);
Cell_value_string_before = (String) cell_value;
}
}
}
}
public test_table() {
setIconImage(Toolkit.getDefaultToolkit().getImage(test_table.class.getResource("/com/sun/java/swing/plaf/windows/icons/Computer.gif")));
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 688, 589);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
xframeWidth = screenSize.width; //dynamic size for frame x-axes
yframeHeight = screenSize.height; //dynamic size for frame y-axes
int xlocation = xframeWidth*2; //dynamic location x-axes
int ylocation = yframeHeight*2; //dynamic location y-axes
setBounds(0,0, xframeWidth, yframeHeight);
setResizable(false);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Αρχείο");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Εξαγωγή σε .txt αρχείο");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser =new JFileChooser();
fileChooser.setDialogTitle("Δημιουργία αρχείου .txt");
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt", "text");
fileChooser.setFileFilter(filter);
int returnVal = fileChooser.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
File newfile = new File(file.getPath()+".txt");
// PrintWriter os = new PrintWriter(file);
FileWriter fw = new FileWriter(newfile,true); //filewriter
BufferedWriter bw = new BufferedWriter(fw); //buffered writer
PrintWriter os = new PrintWriter(bw, true);
os.print("");
for (int col = 0; col < table.getColumnCount(); col++) {
os.print(table.getColumnName(col) + "\t");
os.print(";");
}
os.println("");
os.println("");
for (int row = 0; row < table.getRowCount(); row++) {
for (int col = 0; col < table.getColumnCount(); col++) {
//os.print(table.getColumnName(col) + "\t");
// os.print(": ");
os.print(table.getValueAt(row, col) + "\t");
os.print(";");
// os.print(table.getRowCount() + "\t");
}
os.println("");
}
os.close();
System.out.println("Done!");
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
mnNewMenu.add(mntmNewMenuItem_1);
JMenuItem mntmNewMenuItem_2 = new JMenuItem("Εκτύπωση");
mntmNewMenuItem_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (! table.print()) {
System.err.println("User cancelled printing");
}
} catch (java.awt.print.PrinterException e1) {
System.err.format("Cannot print %s%n", e1.getMessage());
}
}
});
mnNewMenu.add(mntmNewMenuItem_2);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// data_connector getdata1 = new data_connector();
// host = getdata1.getHost();
// username = getdata1.getUsername();
// password1 = getdata1.getPassword();
// mysql_command = getdata1.getMysql_command();
// command_name = getdata1.getCommand_name();
//setTitle(command_name);
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/υπαλληλοι απε-μπε";
String userid = "ziorange";
String password = "120736";
String sql = "SELECT * FROM `ΥΠΑΛΛΗΛΟΙ 2 test`";
//String sql = "SELECT `ΚΩΔΙΚΟΣ`,`ΕΠΩΝΥΜΟ`,`ΟΝΟΜΑ`,`ΟΝΟΜΑ ΠΑΤΡΟΣ`,`ΑΜΚΑ`,`ΑΡΙΘΜΟΣ ΜΗΤΡΩΟΥ ΙΚΑ (αν υπάρχει)` FROM `ΥΠΑΛΛΗΛΟΙ 2` WHERE `ΚΩΔΙΚΟΣ`>'0' AND `ΗΜΕΡΟΜΗΝΙΑ ΑΠΟΧΩΡΗΣΗΣ`>'2009-12-31 00:00:00' OR `ΕΙΔΙΚΟΤΗΤΑ` !='ΑΝΤΑΠΟΚΡΙΤΗΣ ΕΞ' AND `ΛΟΓΟΣ ΑΠΟΧΩΡΗΣΗΣ`='-' ORDER BY `ΕΠΩΝΥΜΟ`";
// Java SE 7 has try-with-resources
// This will ensure that the sql objects are closed when the program
// is finished with them
try
{
connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
//
System.out.println( e.getMessage() );
JOptionPane.showMessageDialog(null, e.getMessage() );
mysql_fail_flag=1;
}
// Create Vectors and copy over elements from ArrayLists to them
// Vector is deprecated but I am using them in this example to keep
// things simple - the best practice would be to create a custom defined
// class which inherits from the AbstractTableModel class
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
contentPane.setLayout(null);
// Create table with database data
table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setColumnSelectionAllowed(true); //epilegei to kathe keli ksexwrista
table.getSelectionModel().addListSelectionListener(
new RowColumnListSelectionListener());
table.getDefaultEditor(String.class).addCellEditorListener(
new CellEditorListener() {
public void editingCanceled(ChangeEvent e) {
System.out.println("editingCanceled");
}
public void editingStopped(ChangeEvent e) {
System.out.println("editingStopped: apply additional action");
rowIndexStart = table.getSelectedRow();
rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
colIndexStart = table.getSelectedColumn();
colIndexEnd = table.getColumnModel().getSelectionModel().getMaxSelectionIndex();
for ( i = rowIndexStart; i <= rowIndexEnd; i++) {
for ( j = colIndexStart; j <= colIndexEnd; j++) {
Object cell_value = table.getValueAt(i,j);
Cell_value_string_after = (String) cell_value;
ia=i+1;
ja=j+1;
column_name_selected2 = table.getColumnName(ja-1);
}
}
if(Cell_value_string_before.equals(Cell_value_string_after)){
System.out.println("Do nothing");
}
else{
System.out.println("UPDATE DATABASE");
update_database();
}
}
});
JScrollPane scrollPane = new JScrollPane( table );
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(5, 5, xframeWidth-20, yframeHeight-70);
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
buttonPanel.setBounds(5, 856, 1574, 1);
getContentPane().add( buttonPanel );
buttonPanel.setLayout(null);
}
public void update_database(){
Object get_lastname = table.getValueAt(ia-1, 5);
String get_lastname_string = (String) get_lastname;
Object get_name = table.getValueAt(ia-1, 6);
String get_name_string=(String) get_name;
System.out.println("RESULT= "+ column_name_selected2 + " - "+Cell_value_string_after+ " - " + get_lastname_string+ " - " + get_name_string );
if(column_name_selected2.equals("ΕΠΩΝΥΜΟ") || column_name_selected2.equals("ΟΝΟΜΑ")){
JOptionPane.showMessageDialog(null, "To επώνυμο και το όνομα δεν μπορεί να αλλάξει","Μήνυμα:",JOptionPane.WARNING_MESSAGE);
}
else{
try {
PreparedStatement update = (PreparedStatement) connection.prepareStatement
("UPDATE `ΥΠΑΛΛΗΛΟΙ 2 TEST` SET `" +column_name_selected2+"` = ? WHERE ΕΠΩΝΥΜΟ= ? AND ΟΝΟΜΑ =? ");
update.setString(1,Cell_value_string_after);
update.setString(2,get_lastname_string);
update.setString(3,get_name_string);
int all_edit_query_status=update.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I want to select JTable zeroth row be selected by default
I am using following code but it gets the zeroth to be focused, not selected
jtblProduct.setCellSelectionEnabled(true);
jtblProduct.changeSelection(0, 0, false, false);
jtblProduct.requestFocus();
jtblProduct.scrollRectToVisible(new Rectangle(jtblProduct.getCellRect(0, 0, true)));
When I get the selected row by using the following code it returns -1, which means none selected.
jtblProduct.getSelectedRow()
Please provide me the way to select the zeroth row by default.
I haven't any issue with that, meaning
a) table.changeSelection(row, col, false, false);
or
b) table.getSelectedRow()
maybe everything depends of how is set value for ListSelectionModel
for better help sooner edit your question with a SSCCE
code
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
//Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
/*for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}*/
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
//DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 100));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 100));
sp2.setViewportView(jTable2);
/*final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 100));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);*/
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2);
JPanel panel1 = new JPanel();
//panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.setLayout(new GridLayout(2, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
//panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
System.out.println(table.getSelectedRow());
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableSelectionGood tableSelection = new TableSelectionGood();
}
});
}
}
Have you tried jtable.setRowSelectionInterval(..) ?
Addition from comment: also try jtable.addRowSelectionInterval(..).