Problems with default table model - java

I am creating java editable table, and faced to problem: it "crashes" after reading data. Here is my table:
table.getTableHeader().setReorderingAllowed(false);
tableModel = new DefaultTableModel(new Object[]
{"#","1","2","3","4","5","6","7"},8);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
Reading from txt:
OK4.addActionListener(new ActionListener(){
#Override
File f = new File(fileName);
if(f.exists()){
try {
tableModel = new DefaultTableModel(new Object[]{"#","1","2","3","4","5","6","7"},0);
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] colHeaders = line.split("\\s+");
tableModel.setColumnIdentifiers(colHeaders);
while ((line = br.readLine()) != null) {
String[] data = line.split("\\s+");
tableModel.addRow(data);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}else{
JOptionPane.showMessageDialog(null, "this day is not saved");
};
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setMaxWidth(22);
});
And main problems causing my sum field:
OK3.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int sum=0;
int number;
Object smth;
String Smth;
int kint2 = table.getRowCount()-1;
if(table.getValueAt(kint2, 1)=="total:"){
}else{
tableModel.addRow(new Object[]{});
int a = table.getRowCount()-1;
table.setValueAt("total:", a, 1);
}
for (int j = 2; j < 8; j++) {
for (int i = 0; i < table.getRowCount()-1; i++) {
smth = table.getValueAt(i,j);
Smth = (String) smth;
if (smth==null){
number=0;
}else{
number=Integer.parseInt(Smth);
}
sum=sum+number;
}
table.setValueAt(sum, table.getRowCount()-1, j);
sum=0;
}
}
});
Application stops calculate sum after being read from txt or calculates only first 4 rows sum. Have it something to do with my tableModel?
Thank you for answers.

The problem is that you add new rows with tablemodel and count rows with table. As discussed at "jTable row count VS model row count" your table won't update the rows count so always use tablemodel.getRowCount()

Related

How to append only one line/row for each iteration in appending values to CSV file in Java

I am having some issues in terms of appending data into my CSV file. The problem is that whenever I try to append data into my CSV file on a second time, the second value which is appended to the CSV file comes with the first appended value. It's like it brings the existing value with it when appending to the CSV file. Thus, because of this issue, it results into an array index out of bounds exception in this statement: cust[read2DStringIndex][newVarIndexer] = fromfile[g]; , the data of the CSV file repeats the existing values along with the latest appended values and also the first value is only displayed on my GUI table.
CSV File:
Table:
Here's my source code in writing and reading the CSV:
public void writeCustomerCSV(){ // this creates a CSV file which stores the inputs of the user
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv",true)); // when I set append mode to true, cust[read2DStringIndex][newVarIndexer] = fromfile[g] results to index array out of bounds to 10
StringBuilder sb = new StringBuilder();
int y;
for(int x = 0; x < itemTo2D.length; x++){
if(itemTo2D[x][0] != null){
for(y = 0; y < itemTo2D[0].length; y++){
sb.append(itemTo2D[x][y]);
sb.append(",");
}
}
sb.append("-"); //separation for rows
sb.append(","); // separation for columns
}
bw.write(sb.toString());
bw.close();
}
catch (Exception ex){
}
}
public void readCustomerCSV(){ // reads the contents of the CSV file
String[][] twoDArray = new String[10][7];
int read2DStringIndex = 0;
int newVarIndexer = 0;
DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel(); // table
String[] fromfile = {}; // 1d string for getting the columns(7 columns) of the CSV file
int ak = 0;
int sk = 0;
try{
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
String line;
while ((line = br.readLine()) != null){
fromfile = line.split(","); //separates the columns by a comma
for(int c = 0; c < fromfile.length; c++){
if(fromfile[c].equals("-")){
sk = 0;
ak++;
if(c > 0){
if(!fromfile[c-1].equals("-")){
id = id + 1;
}
}
} else{
twoDArray[ak][sk] = fromfile[c];
sk++;
}
}
}
} catch (Exception ex){
}
for(int g = 0; g < fromfile.length; g++){
if(fromfile[g].equals("-")){ //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array
read2DStringIndex++;
newVarIndexer = 0;
}
else{
cust[read2DStringIndex][newVarIndexer] = fromfile[g]; //cust is the 2D array(declared universal) which is going to display the values to the table
newVarIndexer++;
}
}
for(int h = 0; h < cust.length; h++){ //prints cust (2D array) , just to check what data is being stored
for(int p = 0; p < cust[0].length; p++){
System.out.println(cust[h][p] + ",");
}
}
setrowcount = 0;
for(int r = 0; r < cust.length; r++){
if(setrowcount == 0){
tblmodelll.setRowCount(0);
}
try{
if(cust[r][0].equals("null") == false){
tblmodelll.addRow(cust[r]); //displays the cust(2D array) data to table
}
} catch(Exception e){
}
setrowcount++;
}
}
Is there something missing in my structure of the codes or is my logic in appending the values not right?
Your responses would indeed help me in resolving this issue.
Thank you very much.

How to display Object array in JTable?

This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}

How do i find the mean and median through a csv using an array on a Jframe?

I'm just a tad bit confused, I need to find the median and mode through this code through an array and I want to input it into a textfield since i'm using Jframes.
This is the code i'm using for the actual CSV document, it already reads the files from the CSV, but the mean and median bit is a bit confusing...
public void theSearch() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File("C:\\Users\\Joshua\\Desktop\\Data Set.csv")));
//BufferedReader br = new BufferedReader(new FileReader(new File("H:\\2nd Year\\Programming Group Project\\Data Set.csv")));
List<String[]> elements = new ArrayList<String[]>();
String line = null;
while((line = br.readLine())!=null) {
String[] splitted = line.split(",");
elements.add(splitted);
}
br.close();
setMinimumSize(new Dimension(640, 480));
String[] columnNames = new String[] {
"Reporting period", "Period of coverage", "Breakdown", "ONS code", "Level", "Level description", "Gender", "Indicator value", "CI lower", "CI upper", "Denominator", "Numerator"
};
Object[][] content = new Object[elements.size()][13];{
for(int i=1; i<elements.size(); i++) {
content[i][0] = elements.get(i)[0];
content[i][1] = elements.get(i)[1];
content[i][2] = elements.get(i)[2];
content[i][3] = elements.get(i)[3];
content[i][4] = elements.get(i)[4];
content[i][5] = elements.get(i)[5];
content[i][6] = elements.get(i)[6];
content[i][7] = elements.get(i)[7];
content[i][8] = elements.get(i)[8];
content[i][9] = elements.get(i)[9];
content[i][10] = elements.get(i)[10];
content[i][11] = elements.get(i)[11];
content[i][12] = elements.get(i)[12];
}
};
jTable.setModel(new DefaultTableModel(content,columnNames));
jScrollPane2.setMinimumSize(new Dimension(600, 23));
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
add(jScrollPane2);
//TableModel model = new DefaultTableModel (content, columnNames);
//JTable jTable = new JTable(model);
//jTable.setPreferredScrollableViewportSize(new Dimension(1200, 400));
// TableRowSorter<TableModel> sorted = new TableRowSorter <TableModel>(model);
// jTable.setRowSorter(sorted);
// jTable.setEnabled(false);
// JScrollPane pane = new JScrollPane(jTable);
System.out.println(jTable.getModel().getValueAt(1, 1));
} catch (Exception ex) {
ex.printStackTrace();
}
}
To calculate statistics such as mean and median you need to have numbers rather than strings. So the first thing you need to do is to convert the strings you are reading from the file into the appropriate data type. By far the best way to do this in Java is to create a class to represent objects in each row and then turn your rows into a collection of those objects.
I'm not sure what your rows represent so I'll just call the class Row here:
class Row {
private final int reportingPeriod;
private final int level;
...
public Row(String[] values) {
this.reportingPeriod = Integer.valueOf(values[0]);
this.level = Integer.valueOf(values[1]);
...
}
public int getLevel() {
return level;
}
}
List<Row> rows = new ArrayList<>();
while((line = br.readLine())!=null) {
rows.add(new Row(line.split(","));
}
Or in Java 8:
List<Row> rows = br.lines().map(l -> new Row(l.split(","))).collect(toList());
To find the median and mean:
int[] levels = new int[rows.size()];
int sum = 0;
for (int i = 0; i < rows.size(); i++) {
levels[i] = rows.get(i).getLevel();
sum += levels[i];
}
Arrays.sort(levels);
int median = levels[rows.size() / 2];
double mean = (double)sum / rows.size();
In Java 8 this would be:
int median = rows.stream().mapToInt(Row::getLevel).sorted().skip(rows.size() / 2).findFirst().get();
double mean = rows.stream().mapToInt(Row::getLevel).average().getAsDouble();

Java- How to compare 1D array with 2D array

I have trouble compare 1D array with 2D array. I already import the txt file to 1D array and 2D array. The 1D array contains 20 correct answer (True and False). The 2D array contains 2000 student answers (100 students * 20 answers per student).
I want to design a program that shows the score for each student, which I already tried to program. Can you help me to figure out which part I did wrong?
The second part of the program is to print out for each question, how many student got right for each question?
Thank you so much!!
import java.io.*;
import java.util.Arrays;
public class Scores
{
public static void main(String[] args) {
try {
File AnswerFile = new File("/Users/shaovera/NetBeansProjects/Scores/QuestionAnswer.txt");
FileReader AnswerReader = new FileReader(AnswerFile);
BufferedReader answerreader = new BufferedReader(AnswerReader);
String[] words = new String[20];
for(int a = 0; a < words.length; a++) {
words[a] = answerreader.readLine();
System.out.println(words[a]);
}
answerreader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
try {
File StudentFile = new File("/Users/shaovera/NetBeansProjects/Scores/StudentAnswer.txt");
FileReader StudentReader = new FileReader(StudentFile);
BufferedReader studentreader = new BufferedReader(StudentReader);
String[][] table = new String[100][20];
for (int i = 0; i < table.length; i++) {
for(int j = 0; j < table[i].length; j++) {
table[i][j] = studentreader.readLine();
System.out.print(table[i][j] + " ");
}
System.out.println("");
}
studentreader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
int count=0;
int student=0;
String[] words = new String[20];
String[][] table = new String[100][20];
for (int column = 0; column < words.length; column++) {
for (int row = 0; row < 100; row++) {
if (words[row] == table[row][column]) {
count++;
student++;
System.out.print("student#" + student + ":" + count);
}
}
}
}
I think this correct code (I wrote comment in line when you have problems)
public static void main(String[] args){
String[]words= new String[20]; // before load from file
String[][]table =new String[100][20]; // before load from file
try{
File AnswerFile=new File("/Users/shaovera/NetBeansProjects/Scores/QuestionAnswer.txt");
FileReader AnswerReader = new FileReader(AnswerFile);
BufferedReader answerreader = new BufferedReader(AnswerReader);
for(int a=0; a<words.length;a++){
words[a]=answerreader.readLine();
System.out.println(words[a]);
}
answerreader.close();
}
catch (Exception ex){
ex.printStackTrace();
}
try{
File StudentFile=new File("/Users/shaovera/NetBeansProjects/Scores/StudentAnswer.txt");
FileReader StudentReader = new FileReader(StudentFile);
BufferedReader studentreader = new BufferedReader(StudentReader);
for (int i = 0; i <table.length; i++) {
for(int j=0;j < table[i].length; j++){
table[i][j]= studentreader.readLine();
System.out.print(table[i][j]+" ");
}
System.out.println("");
}
studentreader.close();
}
catch (Exception ex){
ex.printStackTrace();
}
for (int column = 0; column < words.length; column++) {
int student = 0;
for (int row = 0; row < table.length; row++) {
if (Objects.equals(words[column],table[row][column])) {
student++;
}
}
System.out.println("student#" + student + ":" + column);
}
}

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