This is a JDBC project. Data from a MySQL database on a WAMP server is displayed in a JTable. I want a user-entered ID on my JSpinner to delete the row with that ID from the table. I made a SQL Query and everything works, but the data on the my JTable doesn't refresh when my query is executed. I click my JNazad button (my back button), and reenter that window so that my JTable shows refreshed data. I don't implemented FireTableModel in my NapraviTablicu method, because its DefaultTableModel, and updates are automatically done with it . I don't know what I did wrong:
public class GUIBDelete extends JFrame{
private SpinnerModel SM;
private JSpinner Spinner;
private JLabel LUnos;
private JButton BNazad, BIzvrsi;
private String ID, SqlQuery;
private Vector NaziviKolona = new Vector();
private Vector Podaci = new Vector();
private JTable Tablica=new JTable();
private JScrollPane ScrollPane;
private DefaultTableModel model;
private JTable NapraviTablicu(){
try {
String SqlQuery = "SELECT * FROM `nfc_baza`";
Podaci.clear();
NaziviKolona.clear();
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://"
+ "localhost:3306/nfc", "root", "");
Statement Stat = con.createStatement();
ResultSet Rez = Stat.executeQuery(SqlQuery);
ResultSetMetaData md = Rez.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
NaziviKolona.addElement(md.getColumnName(i));
}
while (Rez.next()) {
Vector red = new Vector(columns);
for (int i = 1; i <= columns; i++) {
red.addElement(Rez.getObject(i));
}
Podaci.addElement(red);
}
Rez.close();
Stat.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
model = new DefaultTableModel(Podaci, NaziviKolona);
JTable table = new JTable(model);
return table;
}
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
dispose();
new GUIIzbornik();
}
};
ActionListener a2 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
ID=null;
SqlQuery = "DELETE FROM `nfc`.`nfc_baza` WHERE `nfc_baza`.`ID` = ";
IzvrsiQuery();
}
private void IzvrsiQuery() {
Object sp = Spinner.getValue();
ID = sp.toString();
SqlQuery=SqlQuery+ID;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con2 = DriverManager.getConnection(
"jdbc:mysql://" + "localhost:3306/nfc", "root", "");
Statement Stat = con2.createStatement();
int Rez = Stat.executeUpdate(SqlQuery);
Stat.close();
con2.close();
JOptionPane.showMessageDialog(null, "Uspješno izvrseno!",
"Poruka!", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
System.out.println(e);
}
}
};
GUIBDelete(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
Tablica=NapraviTablicu();
ScrollPane = new JScrollPane(Tablica);
c.fill = GridBagConstraints.BOTH;
c.insets = new Insets(2, 2, 2, 2);
c.weightx = 0.1;
c.weighty = 0.1;
c.gridwidth = 4;
c.gridheight = 2;
c.gridx = 0;
c.gridy = 0;
add(ScrollPane, c);
LUnos= new JLabel("<html><br>Unesite ID elementa</br> kojeg želite obrisati:<html>");
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.gridheight = 1;
add(LUnos, c);
SM = new SpinnerNumberModel(1, 1, 1000, 1);
Spinner = new JSpinner(SM);
c.gridx = 2;
c.gridy = 2;
c.gridwidth = 2;
add(Spinner, c);
BNazad = new JButton("Nazad");
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
BNazad.addActionListener(a1);
add(BNazad, c);
BIzvrsi = new JButton("Izvrši");
c.gridx = 2;
c.gridy = 3;
BIzvrsi.addActionListener(a2);
add(BIzvrsi, c);
setSize(400, 500);
setTitle("Brisanje podataka");
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUIBDelete i = new GUIBDelete();
}
});
}
}
It looks like you're deleting a row from a database table, and you want the JTable to reflect the change. In izvrsiQuery() update your TableModel and the JTable will update itself. For example,
...
con2.close();
model.removeRow(((Number)(spinner.getValue())).intValue() - 1);
JOptionPane.showMessageDialog(...);
...
Note that row numbers start at 0, and they must be translated when using a RowSorter.
As an aside, your code will be easier for others to read if you use common Java naming conventions and factor out constants.
Addendum: The example just removes a row by number. You'll have to search your TableModel for the row that corresponds to the deleted ID.
Addendum: Although less practical, you may want to refresh the entire table from the database after a DML operation using setModel(), as shown here.
Related
I wrote the following code that I thought would work, I wanted to open a new JFrame on a button click that shows a progress bar that gets updated:
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int numOfRows = getRows();//function that returns number of rows
int numOfColumns = getColumns();//function that returns number of columns
String myquery = "select * from foo_table";
rs = null;
try {
rs = st.executeQuery(myquery);
// extract column information
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
columnData = new ArrayList<String>(columnCount);
for (int i = 1; i <= columnCount; i++) {
columnData.add(rsmd.getColumnName(i));
}
// sql result data
table_ResQues.setModel(new ListTableModel(Collections.<List<Object>>emptyList(), Collections.<String>emptyList()));
rowData = new ArrayList<List<Object>>();
final JFrame progFrame = new JFrame("Processing...");
JPanel mainPPanel = new JPanel(new BorderLayout());
JProgressBar progBar = new JProgressBar(0,100);
progFrame.setBounds(850,300,400,100);
progFrame.setVisible(true);
progBar = new JProgressBar(0,100);
mainPPanel.add(progBar, BorderLayout.NORTH);
progFrame.add(mainPPanel);
progFrame.setVisible(true);
int countRows = 0;
int area = numOfRows*numOfColumns;
int totalTime = area % 200000;
int xPerSec = totalTime/100;
while (rs.next()) {
row = new ArrayList<Object>(columnCount);
for (int i = 0; i < columnCount; i++) {
row.add(rs.getObject(i + 1));
}
rowData.add(row);
countRows++;
if(countRows*numOfColumns == 200000){
progBar.setValue(xPerSec++);
countRows = 0;
}
}
table_ResQues.setModel(new ListTableModel(rowData, columnData));
}catch (SQLException e1) {
JOptionPane.showMessageDialog(frame, e1.getMessage(), "SQL Exception", JOptionPane.ERROR_MESSAGE);
e1.printStackTrace();
}
});
But when googling my problem I realized it is a threading issue, and I never had any experience with threading or SwingWorker, can anyone help me implement what I want using SwingWorker? Should my while-loop be the one that's running in the background? should it be a class by itself? Sorry, i'm really confused.
I have solved it by creating a new class that extends SwingWorker and overriding it's methods. Thanks for the help in the comments.
I am having some trouble in the placement of sections of my code. I am a high school student, and for a project I am making a flashcards app. I am using read/write to store the user's data. I am having trouble on where to close my buffered reader.
This is some of my code:
try {
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
for (int row=0; row < lineNumber; row++) {
try {
//Reads the set and the subject in the text file
String strSetSubjectLine = br1.readLine();
//Splits the string of set and subject by using the comma
String [] names = strSetSubjectLine.split(",");
strSetName = names[0];
strSubjectName = names[1];
//Finds the line number to see the number of cards in each set
lnr2= new LineNumberReader(new FileReader(new File("C:\\Users\\priceadria\\Desktop\\Words_" + strSetName + ".txt")));
lnr2.skip(Long.MAX_VALUE);
strLineNumber2 = String.valueOf(lnr2.getLineNumber());
lineNumber2 = Integer.parseInt(strLineNumber2);
} catch (IOException | NumberFormatException e) {
strLineNumber2 = "0";
}
//Adds the set name to the set name array
lblDeckName[row] = new JLabel (strSetName);
//Adds all buttons that will be used in the layout into a button array
JButton aryOptions [][] = new JButton [3][lineNumber];
//Defines and formats the Add Words button
JButton btnAddWords = new JButton("Add Words");
btnAddWords.setOpaque(false);
btnAddWords.setContentAreaFilled(false);
btnAddWords.setBorder(null);
btnAddWords.setBorderPainted(false);
//Defines and formats the Play button
JButton btnPlay = new JButton("Play");
btnPlay.setOpaque(false);
btnPlay.setContentAreaFilled(false);
btnPlay.setBorder(null);
btnPlay.setBorderPainted(false);
//Defines and formats the Delete Set button
JButton btnDelete = new JButton("Delete Set");
btnDelete.setOpaque(false);
btnDelete.setContentAreaFilled(false);
btnDelete.setBorder(null);
btnDelete.setBorderPainted(false);
//Adds each button to the array based on the number of sets
aryOptions [0][row] = btnAddWords;
aryOptions [1][row] = btnPlay;
aryOptions [2][row] = btnDelete;
//Formats the GridBagLayout (Spaces are for formatting purposes)
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = row;
layoutBackground.add(lblDeckName[row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx =2;
gbc.gridy = row;
layoutBackground.add(new JLabel (strSubjectName),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = row;
layoutBackground.add(new JLabel(" "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = row;
layoutBackground.add(new JLabel(strLineNumber2),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 5;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 6;
gbc.gridy = row;
layoutBackground.add(aryOptions[0][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 7;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 8;
gbc.gridy = row;
layoutBackground.add(aryOptions[1][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 9;
gbc.gridy = row;
layoutBackground.add(new JLabel(" | "),gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 10;
gbc.gridy = row;
layoutBackground.add(aryOptions[2][row],gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 11;
gbc.gridy = row;
layoutBackground.add(new JLabel(" |"),gbc);
//Creates an action event for the delete set button
btnDelete.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Defines new file reader and buffered reader
FileReader file_to_read2 = new FileReader(path);
BufferedReader br2 = new BufferedReader(file_to_read2);
//Finds the numerical index of the button that was clicked
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br2.readLine()) != null) {
counter ++;
if(intIndex == 0) { //If the index is the first option the normal try/catch returns null pointer, so a new try/catch had to be created
try {
//Finds the name of the set based on what button was clicked
String chosenDeck2 = br2.readLine();
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Creates the path to the file that needs to be deleted
Path p2 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p2);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
//Reads the deck name based on the button that was clicked
String chosenDeck2 = br2.readLine();
//Splits the deck name from the subject
String [] aryDeleteDeck = chosenDeck2.split(",");
deleteDeck = aryDeleteDeck[0];
//Closes the buffered reader and file reader
//Gets the file that needs to be deleted
Path p1 = Paths.get("C:\\Users\\priceadria\\Desktop\\Words_" + deleteDeck + ".txt");
Files.delete(p1);
}
}
br2.close();
file_to_read2.close();
}
catch (HeadlessException | IOException | NumberFormatException e) {
JOptionPane.showMessageDialog(null, e);
}
});
//Creates an action event for the add words button
btnAddWords.addActionListener((ActionEvent a) -> {
//Finds the source of the button that was clicked
String strSource = String.valueOf(a.getSource());
String strSourceCut1 = strSource.substring(25,30);
//Finds the index of the button that was clicked
String [] aryIndex = strSourceCut1.split(",");
String strIndex = aryIndex[0];
try {
//Creates a new file reader and buffered reader
FileReader file_to_read3 = new FileReader(path);
BufferedReader br3 = new BufferedReader(file_to_read3);
//Finds the index value
int intIndex = Integer.parseInt(strIndex)/16;
//Creates a counter to count line numbers
int counter = 0;
while((br3.readLine()) != null) {
//Increases counter value by 1
counter ++;
if(intIndex == 0)
{
try {
//Reads the set and subject for the
String chosenDeck2 = br3.readLine();
//Splits the subject from the set
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
} else if ( counter == intIndex) {
String chosenDeck2 = br3.readLine();
String [] aryDeck = chosenDeck2.split(",");
chosenDeck = aryDeck[0];
}
}
br3.close();
file_to_read3.close();
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
//Opens the new words frame
frmWords s = new frmWords(deckName, newXPoint, newYPoint, chosenDeck);
s.setVisible(true);
});
}
} catch (Exception e ) {
JOptionPane.showMessageDialog(null, e);
}
}
The problem I am facing is when I close my buffered reader "br1". If I close it in the for loop, I get a stream closed error, if I close it after the for loop, my other readers will not work. If I move the declaration of the reader into the for loop and try a try with resources statement, it will read the same line over and over again. If I try to make them all work off 1 buffered reader I get a stream closed error as well.
I am really stuck, and would really appreciate some help.
Thanks :)
You may rearrange your exception handling to use this properly.
try
{
//trying something
}
catch(SomeException e)
{
//we failed
e.printStackTrace();
}
finally
{
//called when we failed or when we succeeded, even after a return; statement
}
EDIT
This will pre-read the file and store the data in an ArrayList. Afterwards it closes the stream.
try {
FileReader file_to_read = new FileReader(path);
BufferedReader br1 = new BufferedReader(file_to_read);
ArrayList<String> linesRead = new ArrayList<String>();
String line = br1.readLine();
while(line != null)
{
linesRead.add(line);
line = br1.readLine();
}
br1.close();
for (int row=0; row < lineNumber; row++) {
try {
//Reads the set and the subject in the text file
String strSetSubjectLine = linesRead.get(row);
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 am making a gui with netbeans. I right clicked a JTable to add event listener for mouse clicked. I added my code to the new method. For the life of me when I click the JTable I get no errors.
Any ideas on what I am doing wrong or how to fix it? if you need to see more of my code let me know. everything besides the connection to the DB is ran out of the driver class.
I moved my program to eclipse to make this easier for me to trouble shoot.
private void tableDisplayMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tableDisplay.getSelectedRow();
String tableClick = (tableDisplay.getModel().getValueAt(row, 1).toString());
String sql = " select * from contact where id = ' " + tableClick + " ' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
System.out.println("hey dude this method is being called.");
String add2 = rs.getString("Business_Name");
fieldBN.setText(add2);
String add3 = rs.getString("First_Name");
fieldFN.setText(add3);
String add4 = rs.getString("Last_Name");
fieldLN.setText(add4);
String add5 = rs.getString("Phone");
fieldP.setText(add5);
String add6 = rs.getString("Email");
fieldE.setText(add6);
String add7 = rs.getString("Address_Line_1");
fieldA.setText(add7);
String add8 = rs.getString("Address_Line_2");
aLine2.setText(add8);
String add9 = rs.getString("Website");
fieldW.setText(add9);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Here is the onclick method
Here is my even listener
public Driver() {
gui();
conn = DbConnect.ConnectDb();
UpdateTable();
tableDisplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableDisplayMouseClicked(evt);
}
});
}
Here is the whole Driver Class:
import java.awt.BorderLayout;
public class Driver {
private JFrame f;
private JPanel p;
private JTextField fieldBN;
private JTextField fieldFN;
private JTextField fieldLN;
private JTextField fieldP;
private JTextField fieldE;
private JTextField fieldA;
private JTextField aLine2;
private JTextField fieldW;
private JLabel labelBN;
private JLabel labelFN;
private JLabel labelLN;
private JLabel labelP;
private JLabel labelE;
private JLabel labelA;
private JLabel labelW;
private JComboBox relationship;
private JButton buttonS;
private JTable tableDisplay;
String[] relationshipValues = { "Business", "Friend", "Family", "Professional" };
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
// Constructor:
public Driver() {
gui();
conn = DbConnect.ConnectDb();
UpdateTable();
tableDisplay.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableDisplayMouseClicked(evt);
}
});
}
public void gui() {
f = new JFrame("Contact Book");
GridBagConstraints c = new GridBagConstraints();
p = new JPanel(new GridBagLayout());
f.getContentPane().add(p, BorderLayout.NORTH);
c.gridx = 0;
c.gridy = 0;
labelBN = new JLabel ("Business Name:");
p.add(labelBN, c);
c.gridx = 1;
c.gridy = 0;
fieldBN = new JTextField(10);
p.add(fieldBN, c);
c.gridx = 0;
c.gridy = 1;
labelFN= new JLabel ("First Name:");
p.add(labelFN, c);
c.gridx = 1;
c.gridy = 1;
fieldFN = new JTextField (10);
p.add(fieldFN, c);
c.gridx = 0;
c.gridy = 2;
labelLN= new JLabel ("Last Name:");
p.add(labelLN, c);
c.gridx = 1;
c.gridy = 2;
fieldLN = new JTextField (10);
p.add(fieldLN, c);
c.gridx = 0;
c.gridy = 3;
labelP = new JLabel ("Phone Number:");
p.add(labelP, c);
c.gridx = 1;
c.gridy = 3;
fieldP = new JTextField (10);
p.add(fieldP, c);
c.gridx = 0;
c.gridy = 4;
labelE = new JLabel ("Email:");
p.add(labelE, c);
c.gridx = 1;
c.gridy = 4;
fieldE = new JTextField (10);
p.add(fieldE, c);
c.gridx = 0;
c.gridy = 5;
labelA = new JLabel ("Address:");
p.add(labelA, c);
c.gridx = 1;
c.gridy = 5;
fieldA = new JTextField (10);
p.add(fieldA, c);
c.gridx = 1;
c.gridy = 6;
aLine2 = new JTextField (10);
p.add(aLine2, c);
c.gridx = 0;
c.gridy = 7;
labelW = new JLabel ("Website:");
p.add(labelW, c);
c.gridx = 1;
c.gridy = 7;
fieldW = new JTextField (10);
p.add(fieldW, c);
c.gridx = 0;
c.gridy = 8;
labelW = new JLabel ("Relationship:");
p.add(labelW, c);
c.gridx = 1;
c.gridy = 8;
relationship = new JComboBox(relationshipValues);
p.add(relationship, c);
c.gridx = 1;
c.gridy = 9;
buttonS = new JButton("Save:");
p.add(buttonS, c);
c.gridx = 0;
c.gridy = 10;
tableDisplay = new JTable();
p.add(tableDisplay, c);
// pack the frame for better cross platform support
f.pack();
// Make it visible
f.setVisible(true);
f.setSize(1400,900); // default size is 0,0
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} // End of Gui Method
private void UpdateTable() {
try {
String sql = "SELECT * FROM contact";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
tableDisplay.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void tableDisplayMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tableDisplay.getSelectedRow();
String tableClick = (tableDisplay.getModel().getValueAt(row, 1).toString());
String sql = " select * from contact where id = ' " + tableClick + " ' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
if(rs.next()) {
System.out.println("hey dude this method is being called.");
String add2 = rs.getString("Business_Name");
fieldBN.setText(add2);
String add3 = rs.getString("First_Name");
fieldFN.setText(add3);
String add4 = rs.getString("Last_Name");
fieldLN.setText(add4);
String add5 = rs.getString("Phone");
fieldP.setText(add5);
String add6 = rs.getString("Email");
fieldE.setText(add6);
String add7 = rs.getString("Address_Line_1");
fieldA.setText(add7);
String add8 = rs.getString("Address_Line_2");
aLine2.setText(add8);
String add9 = rs.getString("Website");
fieldW.setText(add9);
}
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Driver();
}
});
} // End main Method
} // End class Driver
It's difficult to know why you're having issues with the registering a MouseListener, there's not enough context to diagnose the problem.
You should start by placing out put statements in the code to check to see if the method is been called and that the query is returning values.
If all else fails, you should try regsitering the mouse listener manually. See How to Write a Mouse Listener for more details.
You query is also including spaces in the match...
String sql = " select * from contact where id = ' " + tableClick + " ' ";
^------------------^-----
Which will affect the ability for the database to match results to your query. Try removing these
String sql = " select * from contact where id = '" + tableClick + "'";
For some reason every time I have someone run this program in Vista it works flawlessly but as soon as I move it over to a Windows 7 PC it stops in the middle of the ActionListener's Action Performed Method meaning I can click my choices but it will never say size selected.
Is there any way to fix this?
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SizerFrame extends JFrame {
ButtonGroup buttons = new ButtonGroup();
JTextField width = new JTextField(2);
JTextField height = new JTextField(2);
double inchesPerTimeline = 2.1;
public SizerFrame()
{
super("Timeline Application");
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(screen.width/2-125,screen.height/2-90,250,180);
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
int[] gridX = new int[]{0,0,0,0};
int[] gridY = new int[]{0,1,2,3};
int[] gridW = new int[]{1,1,2,5};
String[] titles = new String[]{"6\"","9\"","10\"","Custom"};
String[] actions = new String[]{"6","9","10","C"};
for (int a = 0; a < 4; a++)
{
JRadioButton current = new JRadioButton(titles[a]);
current.setActionCommand(actions[a]);
c.gridx = gridX[a];
c.gridy = gridY[a];
c.gridwidth = gridW[a];
buttons.add(current);
getContentPane().add(current,c);
}
c.gridwidth = 1;
String[] title = new String[]{" ","Width","Height"};
gridX = new int[]{9,10,12};
for (int a = 0; a< 3; a++)
{
c.gridx = gridX[a];
getContentPane().add(new JLabel(title[a]),c);
}
c.gridx = 11;
getContentPane().add(width,c);
c.gridx = 13;
getContentPane().add(height,c);
c.gridx = 11;
c.gridy = 0;
c.gridwidth = 2;
JButton button = new JButton("Done");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel x = buttons.getSelection();
String size = "XXX";
System.out.println("Getting screen resolution");
int screenRes = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println("Successfully got screen resolution");
if (x!=null)
size = x.getActionCommand();
try{
TimeTable.width = new Integer(size)*screenRes;
TimeTable.height = (int)((TimeTable.titleCount+1)*inchesPerTimeline*screenRes);
}
catch(NumberFormatException ex)
{
try{
TimeTable.width = (int)(new Double(width.getText().trim())*screenRes);
TimeTable.height = (int)(new Double(height.getText().trim())*screenRes);
}
catch (NumberFormatException except)
{
return;
}
}
TimeTable.ready = true;
System.out.println("Size selected");
dispose();
}
});
getContentPane().add(button,c);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent winEvt){
System.exit(0);
}
});
setVisible(true);
}
}
Concise explanation :
I have a macro that runs out of Excel in Windows Vista and I tried to distribute it to a Computer running Windows 7. Upon execution the code failed to continue executing after this point i.e. it never printed out the words "Size selected". The rest of the program brings in a csv file from a C:\Users\?\AppData\TimeLineMacroProgram folder and later creates an image in the same directory. But this is the portion of the code that is currently broken. Whenever the GUI pops up I select the option for 9" and click done which should pass in 9 as a parameter and then print out "Size Selected" but it doesn't it only disposes the window. Please help.
Longshot guess:
There is an exit from your action listener if width and height text fields don't have content: you return after two NumberFormatExceptions. This would prevent "Size selected" from being displayed, and not dispose the frame. If you got the output "Successfully got screen resolution" and then it appeared to stop working, this could possibly be why. But if you experience that, and then click something else and then Done, it would print size selected.