Java Swing - Unable access jTable from different function - java

I've created jTable as per below:
public void refTable(String jobNo) {
Report rp = new Report();
final String noJob = jobNo;
Map<Integer, String> jMap = rp.getReportInfo(jobNo);
Map<Integer, String> sortedMap = new TreeMap<Integer, String>(jMap);
String[] row = new String[sortedMap.size()];
Integer[] no = new Integer[sortedMap.size()];
String[] stat = new String[sortedMap.size()];
Boolean[] dev = new Boolean[sortedMap.size()];
String[] remark = new String[sortedMap.size()];
Boolean[] rem = new Boolean[sortedMap.size()];
String userRemark[] = new String[sortedMap.size()];
tabSize = sortedMap.size();
int i = 0;
for (Integer key : sortedMap.keySet()) {
no[i] = key;
String []val = sortedMap.get(key).split("###");
if (val[0].trim().equals("DEV")) {
stat[i] = "FAIL";
} else {
stat[i] = val[0].trim();
}
String []strRemark = val[1].split("No");
//tempRemark = strRemark[0];
RemarkDropDownList.devTempValue =val[1].split("No");
row[i] = strRemark[0].trim().replaceAll("Yes", "");//
//row[i] = val[1].trim();
if(strRemark.length<2)
dev[i] = false;
else
dev[i] = true;
remark[i] = "";
if(strRemark.length<2)
userRemark[i] = "";
else
if(RemarkDropDownList.userOthersReamrk!=null)
userRemark[i] = RemarkDropDownList.userSelectedItem;
else
userRemark[i] = strRemark[1];
//remark[i] = false;
/*if(userRemark1[i]!=null)
userRemark[i] = userRemark1[i];//RemarkDropDownList.userOthersReamrk;
else
userRemark[i] =""; Use when drop down*/
rem[i] = false;
i++;
}
DefaultTableModel model = new DefaultTableModel();
model.fireTableDataChanged();
jTable1.setModel(model);
model.addColumn("No:", no);
model.addColumn("Status:", stat);
model.addColumn("Details:", row);
model.addColumn("Non-Deviation", dev);
model.addColumn("Remarks", remark);
model.addColumn("Remove", rem);
model.addColumn("UR", testRemark);
TableColumn col1 = jTable1.getColumnModel().getColumn(0);
col1.setPreferredWidth(30);
TableColumn col2 = jTable1.getColumnModel().getColumn(1);
col2.setPreferredWidth(30);
TableColumn col3 = jTable1.getColumnModel().getColumn(2);
TextRenderer renderer = new TextRenderer();
col3.setCellRenderer(renderer);
col3.setPreferredWidth(350);
CellRenderer cellRender = new CellRenderer();
TableColumn col4 = jTable1.getColumnModel().getColumn(3);
col4.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col4.setCellRenderer(cellRender);
col4.setPreferredWidth(50);
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addTableButtonListener(new TableButtonListener() {
//#Override
public void tableButtonClicked(int row, int col) {
RemarkDropDownList rmk = new RemarkDropDownList(noJob, row);
}
});
TableColumn col5 = jTable1.getColumnModel().getColumn(4);
col5.setCellRenderer(buttonEditor);
col5.setCellEditor(buttonEditor);
TableColumn col6 = jTable1.getColumnModel().getColumn(5);
col6.setCellEditor(jTable1.getDefaultEditor(Boolean.class));
col6.setCellRenderer(jTable1.getDefaultRenderer(Boolean.class));
col6.setPreferredWidth(50);
jTable1.setShowGrid(true);
jTable1.setGridColor(Color.BLACK);
jTable1.setAutoCreateRowSorter(true);
}
I tried to clear jTable from different function in same class like this.
public void clear()
{
jTable1.setModel(new DefaultTableModel());
}
The jTable is not cleared as per expected. When i try to move jTable1.setModel(new DefaultTableModel()); to main function refTable() the jTable cleared. To add on, I not only able to clear the jTable, it looks like I don't have access to jTable at all.Please advice.

This will clear the table for you. You must first create the new default table model, then set it, and finally set the row count to 0.
public void clear(){
DefaultTableModel tm=new DefaultTableModel();
jTable1.setModel(tm);
tm.setRowCount(0);
}
Hope this helped.

Related

Repaired Records : Cell information from worksheet created

I'm receiving an error when opening my OpenXML created spreadsheet. The error is as follows.
repaired record : xl/worksheets/sheet.xml partial cell information
private void SavexlsExcelFile(String fullPathName)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Create(fullPathName, SpreadsheetDocumentType.Workbook))
{
WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);
Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet" };
sheets.Append(sheet);
workbookPart.Workbook.Save();
sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
List<List<string>> dataRow = new List<List<string>>();
List<String> dtRow = new List<String>();
Row row = new Row();
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
if (i == 0)
{
Cell dataCell = new Cell();
dataCell.DataType = CellValues.String;
CellValue cellValue = new CellValue();
cellValue.Text = dataGridView1.Columns[j].Name;
dataCell.StyleIndex = 2;
dataCell.Append(cellValue);
row.AppendChild(dataCell);
//dataColumn.Add(dataGridView1.Columns[j].Name);
}
dtRow.Add(dataGridView1.Rows[i].Cells[j].Value.ToString());
}
}
dataRow.Add(dtRow);
sheetData.AppendChild(row);
row = new Row();
foreach (List<string> datarow in dataRow)
{
row = new Row();
foreach(string dtrow in datarow)
{
row.Append(ConstructCell(dtrow, CellValues.String, 2));
}
sheetData.AppendChild(row);
}
worksheetPart.Worksheet.Save();
}
}
private Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
{
return new Cell()
{
CellValue = new CellValue(value),
DataType = new EnumValue<CellValues>(dataType),
StyleIndex = styleIndex
};
}
There are 2 issues here that I can see. The first is that your use of Columns is incorrect. You should use Columns if you wish to control things such as the width of a column. To use Columns correctly, you'll need to add child Column elements. For example (taken from here):
Columns columns = new Columns();
columns.Append(new Column() { Min = 1, Max = 3, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 4, Max = 4, Width = 30, CustomWidth = true });
In your sample you could just remove the following two lines
Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);
The second issue is the StyleIndex you are using; the style doesn't exist in your document because you haven't added it. The easiest thing to do here is to just remove the StyleIndex altogether.
When debugging files like this, it's always worth looking at the OpenXml Productivity Tool. You can open a generated file in the tool and validate it to see what errors you have in your file.
All the text in Excel is stored under a shared string table. You need to insert the string in shared string table:
string text = dataGridView1.Columns[j].Name;
cell.DataType = CellValues.SharedString;
if (!_spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Any())
{
_spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
}
var sharedStringTablePart = _spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
if (sharedStringTablePart.SharedStringTable == null)
{
sharedStringTablePart.SharedStringTable = new SharedStringTable();
}
//Iterate through shared string table to check if the value is already present.
foreach (SharedStringItem ssItem in sharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
{
if (ssItem.InnerText == text)
{
cell.CellValue = new CellValue(ssItem.ElementsBefore().Count().ToString());
SaveChanges();
return;
}
}
// The text does not exist in the part. Create the SharedStringItem.
var item = sharedStringTablePart.SharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());

How Can I populate a JTable from an excel file, as long as there is more than 1 matching element in my Array List? [Java]

[![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());
}
}

apache metamodel queryConstraints

DataSet dataSet = datacontext.query()
.from(table)
.select(colNameArr)
.where(frstCol).eq(dynamicval1).and("").eq("").or("").eq("")....etc
.execute();
Can this be achieved?, can I dynamically decide the constraint, starting from and(), or() ? if so how can we do it?
Example of dynamic SELECT and WHERE clauses:
// Prepare a data context based on plain old Java objects
List<TableDataProvider<?>> tableDataProviders = new ArrayList<TableDataProvider<?>>();
SimpleTableDef tableDef1 = new SimpleTableDef("snippetTableName1", new String[] {"id", "name"});
tableDataProviders.add(new ArrayTableDataProvider(tableDef1,
new ArrayList<Object[]>()));
PojoDataContext dataContext = new PojoDataContext("snippetSchemaName", tableDataProviders);
// Add some rows
dataContext.executeUpdate(new UpdateScript() {
public void run(UpdateCallback callback) {
callback.insertInto("snippetTableName1").value("id", "id1").value("name", "name1").execute();
callback.insertInto("snippetTableName1").value("id", "id2").value("name", "name2").execute();
}
});
// Prepare dynamic query
String[] selectArray = new String[2];
selectArray[0] = "id";
selectArray[1] = "name";
Map<String, Object> whereClauses = new HashMap<String, Object>();
whereClauses.put("id", "id1");
whereClauses.put("name", "name1");
SatisfiedSelectBuilder<?> queryBuilder = dataContext.query().from("snippetTableName1").select(selectArray);
SatisfiedWhereBuilder<?> whereBuilder = null;
int i = 0;
for (Map.Entry<String, Object> whereClause: whereClauses.entrySet()) {
if (i == 0) {
whereBuilder = queryBuilder.where(whereClause.getKey()).eq(whereClause.getValue());
} else {
whereBuilder = whereBuilder.and(whereClause.getKey()).eq(whereClause.getValue());
}
i++;
}
DataSet dataSet = whereBuilder.execute();
while (dataSet.next()) {
Row row = dataSet.getRow();
System.out.println("Row: " + row);
}

How to populate a JTable using List<Object>

So I need to populate a JTable using data from
List<Object[]> results = query.getResultList();
I'm using NetBeans. I have tried many different things that haven't seemed to work for me.
This is my code:
public void login()
{
Query queryPK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.email, t.user_id FROM usertbl t");
Query queryFK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.curreny, t.amount FROM CURRENCY t WHERE user_fk=?1 ");
List<Object[]> results = queryPK.getResultList();
for(int i = 0; i < results.size(); i++)
{
if(results.get(i)[0].equals(loginEmail))
{
int fk = (int)(results.get(i)[1]);
System.out.println(fk);
queryFK.setParameter(1, fk);
List<Object[]> currencyTBLresluts = queryFK.getResultList();
Currency cur = new Currency();
String[] currTBLheadings = {"Currency","Amount"};
// This is where I would put the data into the table
// Not sure how I am meant to do that
// jTableCurr.setModel(); maybe?
}
}
}
This is an one of many example that you could use it:
//declaring columns
String col[] ={"Currency", "Amount"};
//TableModel
DefaultTableModel tableModel = new DefaultTableModel (col,0);
//Your awesome table with tableModel *injected*
JTable table = new JTable(tableModel);
public void login() {
Query queryPK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.email, t.user_id FROM usertbl t");
Query queryFK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.curreny, t.amount FROM CURRENCY t WHERE user_fk=?1 ");
List<Object[]> results = queryPK.getResultList();
for(int i = 0; i < results.size(); i++) {
if(results.get(i)[0].equals(loginEmail)) {
int fk = (int)(results.get(i)[1]);
System.out.println(fk);
queryFK.setParameter(1, fk);
List<Object[]> currencyTBLresluts = queryFK.getResultList();
if(currencyTBLresluts != null && !currencyTBLresluts.isEmpty()){
Object[] array = currencyTBLresluts.toArray(new Object[currencyTBLresluts.size()]);
((DefaultTableModel)table.getModel()).addRow(array);
}
}
}
}
I came right after looking though the api
public void whenUserLogsIn(){
Query queryPK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.email, t.user_id FROM usertbl t");
Query queryFK = CryptoCurrencyPUEntityManager.createNativeQuery("SELECT t.curreny, t.amount FROM CURRENCY t WHERE user_fk=?");
List<Object[]> results = queryPK.getResultList();
for(int i = 0; i < results.size(); i++)
{
Object[] userArr = results.get(i);
if(userArr[0].equals(loginEmail))
{
int userID = (int)(userArr[1]);
System.out.println(userID);
queryFK.setParameter(1, userID);
List<Object[]> currencyTBLresluts = queryFK.getResultList();
System.out.println("No of currency "+ currencyTBLresluts.size());
String[] currTBLheadings = {"Currency","Amount"};
DefaultTableModel model = new DefaultTableModel(currTBLheadings, currencyTBLresluts.size());
for (Object[] currencyTBLreslut : currencyTBLresluts)
{
model.addRow(currencyTBLreslut);
System.out.println(currencyTBLreslut[0]);
}
jTableCurr.setModel(model);
}
}
}

Insert data to MySQL table from JTable in Java GUI

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();
}
}
}
}

Categories