codice:
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import java.beans.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import javax.swing.JInternalFrame;
import java.text.SimpleDateFormat;
import com.toedter.calendar.*;
import java.util.Vector;
import javax.swing.table.*;
import java.io.*;
import java.util.*;
public class ControlloLog extends JFrame {
private JDesktopPane desktop;
private JDateChooser c2;
private JDateChooser c3;
private String data_inizio;
private String data_fine;
private String selectedItem;
private String[] items;
private JComboBox combobox;
private JPopupMenu pop;
private ResultSet result1;
private int rows;
private TableSQL tables;
private PrintWriter pw;
public ControlloLog(){
super("Controllo Log Magazzino");
setSize(800,600);
JToolBar toolbar = createToolBar();
desktop = new JDesktopPane();
getContentPane().add(BorderLayout.NORTH,toolbar);
getContentPane().add(BorderLayout.CENTER,desktop);
setVisible(true);
}
protected JToolBar createToolBar() {
JToolBar tb = new JToolBar(JToolBar.HORIZONTAL);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
JButton generateButton = new JButton(" Verifica Log ");
ActionListener listener = new GenerateButtonActionListener();
generateButton.addActionListener(listener);
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Fallito il caricamento dei driver SQL.","ERRORE CARICAMENTO DRIVER SQL",JOptionPane.ERROR_MESSAGE);
return (null);
}
try {
Connection conn = null;
// Query SQL
String SQL_conta_postazione= "SELECT count (distinct(postazione)) FROM log_lavorazione_baie";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/master", "us", "pw");
Statement selected = conn.createStatement();
//caricamento query SQL
ResultSet result_conta_postazione = selected.executeQuery(SQL_conta_postazione);
result_conta_postazione.next();
int ris_pos=result_conta_postazione.getInt(1);
ris_pos=ris_pos+1;
items = new String[ris_pos];
items[0]="Tutte";
for(int k=1;k<ris_pos; ){
Connection conn1 = null;
String SQL_postazione= "SELECT distinct(postazione) FROM log_lavorazione_baie order by postazione";
conn1 = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/master", "us", "pw");
Statement selected1 = conn1.createStatement();
//caricamento query SQL
ResultSet result_postazione = selected1.executeQuery(SQL_postazione);
while(result_postazione.next()) {
items[k]=""+result_postazione.getInt(1)+"";
k++;
}
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Connessione col database fallita","ERRORE CONNESSIONE DATABASE",JOptionPane.ERROR_MESSAGE);
}
combobox= new JComboBox(items);
selectedItem="Tutte";
ActionListener selectionListener = new SelectionListener();
combobox.addActionListener(selectionListener);
c2= new JDateChooser();
c3= new JDateChooser();
JLabel label_postazione = new JLabel("Postazione ");
c2.setName("Data Inizio");
c3.setName("Data fine");
JLabel label_data_inizio = new JLabel(" Data inizio ");
DateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd");
data_inizio = dateformat1.format(c2.getDate());
JLabel label_spazio = new JLabel(" ");
JLabel label_data_fine = new JLabel(" Data fine ");
DateFormat dateformat2 = new SimpleDateFormat("yyyy-MM-dd");
data_fine = dateformat2.format(c3.getDate());
//Ti permette di scatenare l'evento del cambio data nel calendario con data minore
c2.addPropertyChangeListener (new PropertyChangeListener () {
public void propertyChange (PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("date")) {
DateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd");
data_inizio = dateformat1.format(c2.getDate());
}
}
});
//Ti permette di scatenare l'evento del cambio data nel calendario con data maggiore
c3.addPropertyChangeListener (new PropertyChangeListener () {
public void propertyChange (PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("date")) {
DateFormat dateformat1 = new SimpleDateFormat("yyyy-MM-dd");
data_fine = dateformat1.format(c3.getDate());
}
}
});
//aggiunta alla toolbar dei vari "bottoni"
tb.add(label_postazione);
tb.add(combobox);
tb.add(label_data_inizio);
tb.add(c2);
tb.add(label_data_fine);
tb.add(c3);
tb.add(label_spazio);
tb.add(generateButton);
return tb;
}
//Classe che crea la tabella
class TableSQL extends JInternalFrame {
TableSQL() {
super("log_lavorazione_baie");
setDefaultCloseOperation(JInternalFrame.EXIT_ON_CLOSE);
// n° di colonne
int columns = 6;
// etichette colonne
String[] labels = {"postazione", "data_ora", "udt", "articolo","lotto","quantita"};
// larghezza colonne
int[] widths = {60, 120, 70, 100, 80, 70};
try {
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Fallito il caricamento dei driver SQL.","ERRORE CARICAMENTO DRIVER SQL",JOptionPane.ERROR_MESSAGE);
}
try {
Connection con1=null;
String postazione=selectedItem;
String tempo_min=data_inizio;
String tempo_max=data_fine;
//Connessione col database in cui vengono specificati url, nome utente, password
con1 = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/master", "us", "pw");
Statement select1=con1.createStatement();
Statement select = con1.createStatement();
if(postazione.equalsIgnoreCase("Tutte")){
System.out.println("TUTTE");
// Query SQL
String SQL_rows="SELECT count (postazione) FROM log_lavorazione_baie where data_ora>='" +tempo_min+"' and data_ora<='" +tempo_max+ "%'";
String SQL= "SELECT * FROM log_lavorazione_baie where data_ora>='" +tempo_min+"' and data_ora<='" +tempo_max+ "%'ORDER BY data_ora DESC";
//caricamento query SQL
ResultSet result2=select1.executeQuery(SQL_rows);
result2.next();
int ris_row=result2.getInt(1);
// n° di righe dinamico
rows = ris_row;
result1 = select.executeQuery(SQL);
}
else{
System.out.println("Entra in cambio Combobox");
String SQL_rows_post="SELECT count (postazione) FROM log_lavorazione_baie where postazione='"+postazione+"' and data_ora>='" +tempo_min+"' and data_ora<='" +tempo_max+ "%'";
String SQL_post= "SELECT * FROM log_lavorazione_baie where postazione='"+postazione+"' and data_ora>='" +tempo_min+"' and data_ora<='" +tempo_max+ "%'ORDER BY data_ora DESC";
//caricamento query SQL
ResultSet result2=select1.executeQuery(SQL_rows_post);
result2.next();
int ris_row=result2.getInt(1);
// n° di righe dinamico
rows = ris_row;
result1 = select.executeQuery(SQL_post);
} }
catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null,"Connessione col database fallita","ERRORE CONNESSIONE DATABASE",JOptionPane.ERROR_MESSAGE);
}
// vettore dati tabella
Vector data = new Vector(0, 1);
// vettore colonne tabella
Vector columnNames = new Vector(0, 1);
// popolo la tabella
for(int i = 0; i < rows; i++) {
try {
// vettore singola riga tabella
Vector row = new Vector();
result1.next();
for (int j = 1; j <= columns; j++) {
try {
row.addElement(result1.getString(j));
pw.print(result1.getString(j)+";");
}
catch (SQLException ex) {
Logger.getLogger(ControlloLog.class.getName()).log(Level.SEVERE, null, ex);
}
}
data.addElement(row);
pw.print("\n");
}
catch (SQLException ex) {
Logger.getLogger(ControlloLog.class.getName()).log(Level.SEVERE, null, ex);
}
}
// intestazioni colonne
for(int i = 0; i < columns; i++) {
columnNames.addElement(labels[i]);
}
// modello dati della tabella
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
// modello attributi delle colonne
DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
for(int i = 0; i < columns; i++) {
// modello attributi colonna singola
TableColumn column = new TableColumn(i, widths[i]);
column.setHeaderValue(labels[i]);
columnModel.addColumn(column);
}
// la tabella
JTable table = new JTable(tableModel, columnModel);
table.setPreferredScrollableViewportSize(new Dimension(770, 500));
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
pack();
setLocation(0, 0);
setVisible(true);
}}
// Azioni dei pulsanti
class GenerateButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pw = null;
try {
pw = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Controlli.csv", false)));
pw.print("postazione;data_ora;udt;articolo;lotto;quantita\n");
tables = new TableSQL();
desktop.add(tables);
tables.moveToFront();
pw.close();
} catch (IOException ex) {
Logger.getLogger(ControlloLog.class.getName()).log(Level.SEVERE, null, ex);
}
VisualizzaFile();
}}
public void VisualizzaFile() {
try
{
String nomeFile = "Controlli.csv";
Runtime rt = Runtime.getRuntime();
Process proc;
proc = rt.exec("cmd /C start " + nomeFile);
InputStream inp = proc.getInputStream();
OutputStream outp = proc.getOutputStream();
InputStream errp = proc.getErrorStream();
}
catch (Exception exc)
{
exc.printStackTrace(); } }
class GenerateButtonActionListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
pop.setVisible(false);
}
}
class SelectionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
selectedItem = (String)cb.getSelectedItem();
}
}
class AncestorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
selectedItem = (String)cb.getSelectedItem();
}
}
public static void main(String[] args) {
ControlloLog framec = new ControlloLog();
framec.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}