This is a follow-up question to my post here.
My JTable is populated using abstracttablemodel. I implemented an insertRow method which works perfectly in the database but does not refresh my JTable. As seen in the code below, after the insert, I use the fireTableRowsInserted method to update the model but this doesn't seem to work. The abstracttablemodel with insertRow method is as below:
class ResultSetTableModel extends AbstractTableModel
{
private final Connection connection;
private final Statement statement;
private ResultSet resultSet;
private ResultSetMetaData resultSetMetaData;
private int numberOfRows;
private static final String oracleDriver = "oracle.jdbc.driver.OracleDriver";
//track DB connection status
private boolean dbConnStatus = false;
//constructor initializes rSet and obtains its
//metadata object; also determines number of rows
public ResultSetTableModel(String oracleConnection, String username, String password, String query) throws SQLException
{
//connect to the database
connection = getDBConnection(oracleConnection, username, password);
//create statement to query database
statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//update database connection status
dbConnStatus = true;
//set query and execute it
setQuery(query);
}
private static Connection getDBConnection(String oraConn, String user, String pwd)
{
Connection dbConn = null;
try
{
Class.forName(oracleDriver);
}
catch (ClassNotFoundException classExcep)
{
System.out.println(classExcep.getMessage());
}
try
{
dbConn = DriverManager.getConnection(oraConn, user, pwd);
return dbConn;
}
catch (SQLException sqlExcep)
{
System.out.println(sqlExcep.getMessage());
}
return dbConn;
}
//get class that represents column type
#SuppressWarnings({ "unchecked", "rawtypes" })
public Class getColumnClass(int column) throws IllegalStateException
{
//ensure database connection is available
if(!dbConnStatus)
throw new IllegalStateException("No connection to the Database");
//determine Java class of column
try
{
String className = resultSetMetaData.getColumnClassName(column + 1);
//return Class object that represents class Name
return Class.forName(className);
}
catch (Exception e)
{
e.printStackTrace();
}
return Object.class; //if problems occur above, assume type Object
}
//remove row in the ResultSet
public void removeRow(String empID)
{
int rsRow = 0;
try
{
//set cursor to beginning of data set (before first row)
if(!resultSet.isBeforeFirst())
resultSet.beforeFirst();
//iterate through resultSet to find matching record with
//correct employee ID. once found delete row
while(resultSet.next())
{
if(resultSet.getString("EMPLOYEENO").equals(empID))
{
rsRow = resultSet.getRow();
resultSet.absolute(rsRow);
resultSet.deleteRow();
break;
}
}
resultSet.last();
numberOfRows = resultSet.getRow();
fireTableDataChanged();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
//add row into ResultSet
public void insertRow(String fName, String lName, String userID, String company, String group)
{
//get display name of user
String displayName = fName.substring(0, 1).concat(". ").concat(lName);
try
{
//move cursor to staging row for record insertion
resultSet.moveToInsertRow();
resultSet.updateString("EMPLOYEENO", userID);
resultSet.updateString("FIRSTNAME", fName);
resultSet.updateString("LASTNAME", lName);
resultSet.updateString("DISPLAYNAME", displayName);
resultSet.updateString("GROUPNAME", group);
resultSet.updateString("COMPANYNAME", company);
resultSet.insertRow();
resultSet.beforeFirst();
//resultSet.last();
//row = resultSet.getRow();
//fireTableDataChanged();
//fireTableStructureChanged();
fireTableRowsInserted(this.getRowCount() - 1, this.getRowCount() - 1);
}
catch (SQLException e)
{
e.printStackTrace();
}
}
//get the number of columns in the ResultSet
public int getColumnCount() throws IllegalStateException
{
//ensure database connection is available
if(!dbConnStatus)
throw new IllegalStateException("No connection to the Database");
//determine number of columns
try
{
return resultSetMetaData.getColumnCount();
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
return 0; //if problem occur above, return 0 for number of columns
}
//get name of a particular column in ResultSet
public String getColumnName(int column) throws IllegalStateException
{
//ensure database connection is available
if(!dbConnStatus)
throw new IllegalStateException("No connection to the Database");
//determine column name
try
{
return resultSetMetaData.getColumnName(column + 1);
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
return ""; //if problems occur above, return empty string for column name
}
//return number of rows in ResultSet
public int getRowCount() throws IllegalStateException
{
//ensure database connection is available
if(!dbConnStatus)
throw new IllegalStateException("No connection to the Database");
return numberOfRows;
}
//obtain value in particular row and column
public Object getValueAt(int row, int column) throws IllegalStateException
{
//ensure database connection is available
if(!dbConnStatus)
throw new IllegalStateException("No connection to the Database");
//obtain a value at specified ResultSet row and column
try
{
resultSet.absolute(row + 1);
return resultSet.getObject(column + 1);
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
return ""; //if problems occur above, return empty string object
}
//set new database query string
public void setQuery(String query) throws SQLException, IllegalStateException
{
//ensure database connection is available
if(!dbConnStatus)
throw new IllegalStateException("No connection to the Database");
//specify query and execute it
resultSet = statement.executeQuery(query);
//obtain metadata for ResultSet
resultSetMetaData = resultSet.getMetaData();
//determine number of rows in ResultSet
resultSet.last(); //move to last row
numberOfRows = resultSet.getRow(); //get row number
//notify JTable that model has changed
fireTableStructureChanged();
}
//close Statement and Connection
public void disconnectFromDatabase()
{
//ensure database connection is available
if(dbConnStatus);
//determine number of columns
try
{
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
}
finally
{
dbConnStatus = false;
}
}
} //end class ResultSetTableModel
My custom JFrame class that includes the button call for the insert:
class AdministrationFrame extends JFrame
{
//set default query to retrieve all non-disabled users
private static final String DEFAULT_QUERY =
"SELECT EMPLOYEENO, FIRSTNAME, LASTNAME, DISPLAYNAME, GROUPNAME, COMPANYNAME "
+ "FROM EMPLOYEES "
+ "WHERE DISABLED IS NULL ";
//query to retrieve all groups
private static final String ALL_GROUPS_QUERY =
"SELECT DISTINCT GROUPNAME "
+ "FROM EMPLOYEES "
+ "ORDER BY GROUPNAME ";
private static final String ALL_COMPANIES_QUERY =
"SELECT DISTINCT COMPANYNAME "
+ "FROM EMPLOYEES ";
private static final String ORACLE_CONNECTION = "jdbc:oracle:thin:#..."; //connection to UAT DB
private static final String USERNAME = "...";
private static final String PASSWORD = "...";
//layout for window
private final BorderLayout layout;
private final GridBagLayout gbLayout;
private final GridBagConstraints c;
//administration window
private final JFrame adminFrame;
private final JPanel tablePanel;
private final JPanel tablePanel2;
private final JPanel modifyPanel;
private final JPanel buttonPanel;
//items for tablePanel
private final JLabel filterLabel;
private final JTextField filterTextField;
private final JButton filterButton;
//items for modifyPanel
private final JLabel firstNameLabel;
private final JLabel lastNameLabel;
private final JLabel userIDLabel;
private final JLabel companyLabel;
private final JLabel groupLabel;
private final JTextField firstNameField;
private final JTextField lastNameField;
private final JTextField userIDField;
private final JTextField companyField;
private final JTextField groupField;
private final JComboBox<String> groupsDropDown;
private final JComboBox<String> companiesDropDown;
//items for buttonPanel
private final JButton updateButton;
private Connection conn;
private JTable resultTable;
private static ResultSetTableModel tblModel;
#SuppressWarnings("unchecked")
public AdministrationFrame()
{
layout = new BorderLayout(10, 10);
setLayout(layout);
gbLayout = new GridBagLayout();
c = new GridBagConstraints();
//place GUI components on JFrame's content pane
adminFrame = new JFrame("Employee Modification Panel");
//set up JPanels
tablePanel = new JPanel();
tablePanel2 = new JPanel();
String tablePanelTitle = "Employee Details";
tablePanel.setBorder(BorderFactory.createTitledBorder(null,
tablePanelTitle, TitledBorder.CENTER, TitledBorder.TOP,
new Font("Arial", Font.BOLD + Font.ITALIC, 22), Color.BLACK));
tablePanel2.setLayout(new BoxLayout(tablePanel2, BoxLayout.Y_AXIS));
modifyPanel = new JPanel();
modifyPanel.setLayout(gbLayout);
buttonPanel = new JPanel();
//set up items in each JPanel
filterLabel = new JLabel("Filter:");
filterLabel.setAlignmentX(LEFT_ALIGNMENT);
filterTextField = new JTextField();
filterTextField.setAlignmentX(LEFT_ALIGNMENT);
filterButton = new JButton("Apply Filter");
filterButton.setAlignmentX(LEFT_ALIGNMENT);
firstNameLabel = new JLabel("First Name:");
lastNameLabel = new JLabel("Last Name:");
userIDLabel = new JLabel("Employee ID:");
companyLabel = new JLabel("Company:");
groupLabel = new JLabel("Group:");
firstNameField = new JTextField();
lastNameField = new JTextField();
userIDField = new JTextField();
companyField = new JTextField();
companyField.setEditable(false);
groupField = new JTextField();
groupField.setEditable(false);
updateButton = new JButton("Insert/Modify");
//create custom renderer for the company & group
//drop down menus - changes their behavior
class PromptComboBoxRenderer extends BasicComboBoxRenderer
{
//set the text to display when no item has been selected
private String prompt;
public PromptComboBoxRenderer(String prompt)
{
this.prompt = prompt;
}
#SuppressWarnings("rawtypes")
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if(value == null)
setText(prompt);
return this;
}
}
groupsDropDown = new JComboBox<String>();
groupsDropDown.setRenderer(new PromptComboBoxRenderer("Select a Group"));
groupsDropDown.addItemListener(new ItemListener() //anonymous inner class
{
#Override
public void itemStateChanged(ItemEvent event)
{
if(event.getStateChange() == ItemEvent.SELECTED)
{
if(groupsDropDown.getSelectedItem().toString() != "")
{
String selectedGroup = groupsDropDown.getSelectedItem().toString();
//System.out.println("You selected group: " + selectedGroup);
groupField.setText(selectedGroup);
}
}
}
});
companiesDropDown = new JComboBox<String>();
companiesDropDown.setRenderer(new PromptComboBoxRenderer("Select a Company"));
companiesDropDown.addItemListener(new ItemListener() //anonymous inner class
{
#Override
public void itemStateChanged(ItemEvent event)
{
if(event.getStateChange() == ItemEvent.SELECTED)
{
if(companiesDropDown.getSelectedItem().toString() != "")
{
String selectedCompany = companiesDropDown.getSelectedItem().toString();
//System.out.println("You selected company: " + selectedCompany);
companyField.setText(selectedCompany);
}
}
}
});
//user click "Insert/Modify"
updateButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
tblModel.insertRow(getFirstName(), getLastName(), getUserID(), getCompany(), getGroup());
refreshScreen();
}
});
//create ResultSetTableModel and display database table
try
{
//create TableModel for results of the default query
tblModel = new ResultSetTableModel(ORACLE_CONNECTION, USERNAME, PASSWORD, DEFAULT_QUERY);
//create JTable based on the tblModel
resultTable = new JTable(tblModel)
{
#Override
public Dimension getPreferredScrollableViewportSize()
{
return new Dimension(600, 250);
}
};
resultTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
resultTable.getTableHeader().setResizingAllowed(false); //disable column resizing
resultTable.getTableHeader().setReorderingAllowed(false); //disable column dragging
resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //sets table to only allow selection of single row
resultTable.getSelectionModel().addListSelectionListener(new RowListener()); //register event handlers
final JScrollPane tablePane = new JScrollPane(resultTable);
//add items to JPanels
tablePanel2.add(filterLabel);
tablePanel2.add(Box.createRigidArea(new Dimension(0, 2)));
tablePanel2.add(filterTextField);
tablePanel2.add(Box.createRigidArea(new Dimension(0, 10)));
tablePanel2.add(filterButton);
tablePanel.add(tablePane);
tablePanel.add(tablePanel2);
buttonPanel.add(updateButton);
//fill ComboBoxes
conn = DriverManager.getConnection(ORACLE_CONNECTION, USERNAME, PASSWORD);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet groupResultSet = stmt.executeQuery(ALL_GROUPS_QUERY);
while(groupResultSet.next())
{
String group = groupResultSet.getString("GROUPNAME");
groupsDropDown.addItem(group);
}
groupsDropDown.setSelectedIndex(-1);
groupField.setText("");
ResultSet companiesResultSet = stmt.executeQuery(ALL_COMPANIES_QUERY);
while(companiesResultSet.next())
{
String company = companiesResultSet.getString("COMPANYNAME");
companiesDropDown.addItem(company);
}
companiesDropDown.setSelectedIndex(-1);
companyField.setText("");
//add items to modifyPanel
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 150, 5, 0); //no padding on right for labels
c.gridx = 0;
c.gridy = 0;
modifyPanel.add(firstNameLabel, c);
c.gridx = 0;
c.gridy = 1;
modifyPanel.add(lastNameLabel, c);
c.gridx = 0;
c.gridy = 2;
modifyPanel.add(userIDLabel, c);
c.gridx = 0;
c.gridy = 3;
modifyPanel.add(companyLabel, c);
c.gridx = 0;
c.gridy = 4;
modifyPanel.add(groupLabel, c);
c.insets = new Insets(0, 10, 5, 10); //no padding on top for fields
c.anchor = GridBagConstraints.SOUTH;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.gridx = 1;
c.gridy = 0;
c.gridwidth = 2;
modifyPanel.add(firstNameField, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 2;
modifyPanel.add(lastNameField, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 2;
modifyPanel.add(userIDField, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 2;
modifyPanel.add(companyField, c);
c.gridx = 1;
c.gridy = 4;
c.gridwidth = 2;
modifyPanel.add(groupField, c);
c.insets = new Insets(0, 10, 5, 80); //padding for dropdowns
c.gridx = 4;
c.gridy = 3;
modifyPanel.add(companiesDropDown, c);
c.gridx = 4;
c.gridy = 4;
modifyPanel.add(groupsDropDown, c);
//add JPanels to frame
adminFrame.add(tablePanel, BorderLayout.NORTH);
adminFrame.add(modifyPanel, BorderLayout.CENTER);
adminFrame.add(buttonPanel, BorderLayout.SOUTH);
final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(tblModel);
resultTable.setRowSorter(sorter);
//create listener for filterButton
filterButton.addActionListener(new ActionListener()
{
//pass filter text to Listener
public void actionPerformed(ActionEvent e)
{
String text = filterTextField.getText();
if (text.length() == 0)
sorter.setRowFilter(null);
else
{
try
{
//make filter case-insensitive
sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
}
catch (PatternSyntaxException pse)
{
JOptionPane.showMessageDialog(null, "Bad regex pattern",
"Bad regex pattern", JOptionPane.ERROR_MESSAGE);
}
}
}
});
pack();
//dispose of window when user quits application
//(do not want to close application)
adminFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
adminFrame.setSize(800, 600);
adminFrame.setVisible(true);
adminFrame.setLocationRelativeTo(null);
adminFrame.setResizable(false);
//ensure database is closed when user quits application
adminFrame.addWindowListener(new WindowAdapter()
{
//disconnect from database and exit when window has closed
public void windowClosed(WindowEvent event)
{
tblModel.disconnectFromDatabase();
System.exit(0);
}
});
}
catch (SQLException sqlException)
{
JOptionPane.showMessageDialog(null, sqlException.getMessage(),
"Database error", JOptionPane.ERROR_MESSAGE);
tblModel.disconnectFromDatabase();
System.exit(1); //terminate application
}
}
private class RowListener implements ListSelectionListener
{
#Override
public void valueChanged(ListSelectionEvent event)
{
if(!event.getValueIsAdjusting())
{
int row = resultTable.getSelectedRow();
if(row == -1) //no row found
JOptionPane.showMessageDialog(adminFrame, "Selected row not found in filtered set",
null, JOptionPane.WARNING_MESSAGE);
else
{
firstNameField.setText(resultTable.getValueAt(row, resultTable.getColumn("FIRSTNAME").getModelIndex()).toString());
lastNameField.setText(resultTable.getValueAt(row, resultTable.getColumn("LASTNAME").getModelIndex()).toString());
userIDField.setText(resultTable.getValueAt(row, resultTable.getColumn("EMPLOYEENO").getModelIndex()).toString());
companyField.setText(resultTable.getValueAt(row, resultTable.getColumn("COMPANYNAME").getModelIndex()).toString());
groupField.setText(resultTable.getValueAt(row, resultTable.getColumn("GROUPNAME").getModelIndex()).toString());
}
}
}
};
//refreshes the window after an update
//by clearing out all fields
//and resetting dropdown menus
public void refreshScreen()
{
firstNameField.setText("");
lastNameField.setText("");
userIDField.setText("");
companyField.setText("");
groupField.setText("");
groupsDropDown.setSelectedIndex(-1);
companiesDropDown.setSelectedIndex(-1);
}
//get methods for text fields
public String getFirstName()
{
return firstNameField.getText();
}
public String getLastName()
{
return lastNameField.getText();
}
public String getUserID()
{
return userIDField.getText();
}
public String getCompany()
{
return companyField.getText();
}
public String getGroup()
{
return groupField.getText();
}
}//end class EmpInOutBoard
I noticed other similar posts using abstracttablemodel have used Lists or some other type of collection to modify the underlying result set. Is this something I need with my application as well or am I missing something very basic here?
Thank in advance.
Related
I wnat to fill my Table with new Datas which i get by my DataBase(MySQL). I get all datas and create a new Model with them, but if i want to refresh the specific panel, then it wont be repainted.
public class PanelWest extends JPanel implements ActionListener {
private JButton but_selectBP;
private JButton but_selectBPAdr;
private JButton but_selectGerichte;
private GroupLayout layoutGroup;
private Connector stmtExecuter = new Connector();
// private PanelCenter tableViewer = new PanelCenter();
public PanelWest() {
layoutGroup = createLayout();
this.setLayout(layoutGroup);
createButtons();
}
private GroupLayout createLayout() {
GroupLayout layout = new GroupLayout(this);
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
return layout;
}
void createButtons() {
this.but_selectBP = new JButton("Kunden anzeigen");
this.but_selectBP.addActionListener(this);
this.but_selectBPAdr = new JButton("Gerichte anzeigen");
this.but_selectBPAdr.addActionListener(this);
this.but_selectGerichte = new JButton("Lieferanten anzeigen");
this.but_selectGerichte.addActionListener(this);
this.layoutGroup.setHorizontalGroup(layoutGroup.createParallelGroup().addComponent(but_selectBP).addComponent(but_selectBPAdr).addComponent(but_selectGerichte));
this.layoutGroup.setVerticalGroup(layoutGroup.createSequentialGroup().addComponent(but_selectBP).addComponent(but_selectBPAdr).addComponent(but_selectGerichte));
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if (src.equals(this.but_selectBP)) {
String query = "SELECT * FROM Kunde";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.setTableName("Kunde");
new PanelCenter().createTable(fillHeader(rst), fillData(rst));
}
if (src.equals(this.but_selectBPAdr)) {
String query = "SELECT * FROM Gericht";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.createTable(fillHeader(rst), fillData(rst));
}
if (src.equals(this.but_selectGerichte)) {
String query = "SELECT * FROM Lieferant";
ResultSet rst = this.stmtExecuter.getResultDBData(query);
// this.tableViewer.createTable(fillHeader(rst), fillData(rst));
}
}
private String[] fillHeader(ResultSet rst) {
try {
ResultSetMetaData rstMetaData = rst.getMetaData();
String[] header = new String[rstMetaData.getColumnCount()];
ArrayList<String> headerDetails = new ArrayList<>();
for (int i = 1; i <= rstMetaData.getColumnCount(); i++) {
headerDetails.add(rstMetaData.getColumnName(i));
}
int j = 0;
for(String head : headerDetails){
header[j] = head;
j++;
}
return header;
} catch (SQLException se) {
se.printStackTrace();
}
return null;
}
private Object[][] fillData(ResultSet rst) {
try {
ResultSetMetaData rstMetaData = rst.getMetaData();
int rowCount = 0;
rst.last();
rowCount = rst.getRow();
System.out.println(rowCount + " Rows");
rst.beforeFirst();
Object[][] data = new Object[rowCount][rstMetaData.getColumnCount()];
int row = 0;
while (rst.next()) {
for (int i = 0; i < rstMetaData.getColumnCount(); i++) {
data[row][i] = rst.getObject(i + 1);
}
row++;
}
return data;
} catch (SQLException se) {
System.out.println("Hier bei Fill");
}
return null;
}
}
I use remove, add revalidate and repaint on my jpanel.
void createTable(String[] header, Object[][] data) {
this.tableData = new JTable();
this.tableData.setModel(new MyTableModel(header, data));
this.tableData.setFillsViewportHeight(true);
this.tableData.addKeyListener(this);
this.scrollPaneTable = new JScrollPane(tableData);
this.scrollPaneTable.setSize(500, 500);
this.remove(this.scrollPaneTable);
this.add(this.scrollPaneTable);
this.revalidate();
this.repaint();
}
You don't need to reinitialize the table, table model.
Put some global variables on the top
private MyTableModel tableModel; //Your own table model
private JTable table;
Initialize them on init
public PanelWest() {
layoutGroup = createLayout();
this.setLayout(layoutGroup);
createButtons();
tableModel = new MyTableModel(header, data); //Your own tablemodel
table = new JTable(tableModel); //Hook the model to your table
this.add(table)
//...Do other things else to your table
}
Once you want to update the table, simply clear the rows from the table model and fill with new rows.
And ask JTable to update its data by calling
void createTable(String[] header, Object[][] data){
int cols = header.length;
int rows = data.length;
//Remove all rows from model
tableModel.setRowCount(0); //(As said by HovercraftFullOfEels)
Object[] row = new Object[cols];
for (int j = 0; j < data.length; j++){
for (int i = 0; i < cols; i++){
row[i] = data[j][i];
}
tableModel.addRow(row);
}
tableModel.fireTableDataChanged();
}
Hope it will help.
Thanks for your help.
I add a small test to my createTable method. I create a new window to show the new table datas and it works. i think my jpanel doesn't repaint correctly cause my grouplayout.
this.tableData = new JTable();
this.tableData.setModel(new MyTableModel(header, data));
this.tableData.setFillsViewportHeight(true);
this.tableData.addKeyListener(this);
this.scrollPaneTable = new JScrollPane(tableData);
this.scrollPaneTable.setSize(500, 500);
this.layoutGroup.setVerticalGroup(layoutGroup.createSequentialGroup().addComponent(this.scrollPaneTable, 400, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addComponent(this.scrollPaneChanges).addComponent(this.but_user).addComponent(this.but_dataChange));
// JFrame fr = new JFrame("Hello");
// fr.setLayout(null);
// fr.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// fr.setVisible(true);
// fr.add(this.scrollPaneTable);
i am trying to make an application that sends a number of string added by the user to my SQL server. however when i try to add an string to my jlist from jtextfield it gets added twice..
here is the thing
user adds a name to jtextfield . when he hits the + button it is send to jlist
public void addBrand() {
int index = BrandList.getSelectedIndex(); // get selected index
if (index == -1) { // no selection, so insert at beginning
index = 0;
}
else { // add after the selected item
index++;
}
model.insertElementAt(BrandLbl.getText(), index);
BrandLbl.setText(null);
}
all fine here i see one item added to my jlist
when the user decides the list is complete he hits the "next" button and
the sendArraytoDB(JList list) method is called
public static void sendArraytoDB(JList<String> list){
Connection con = null;
PreparedStatement stm = null;
String updQuery = "insert into brand_names (name) values (?)";
try{
con = DB.getConnection();
//con.setAutoCommit(false);
int x =1;
stm = con.prepareStatement(updQuery);
int f = list.getModel().getSize();
System.out.print(f);
for (int i=0; i<list.getModel().getSize(); i++){
String name =list.getModel().getElementAt(i);
stm.setString(x, name);
//try{
stm.executeUpdate();
//}finally{
//stm.close();
//}
}
}catch(SQLException ex){
System.out.printf("error while sending array to db");
ex.printStackTrace();
}finally{
if (stm != null){
etc etc....
for my bad luck the my databse shows that there are two names sent..
i cant post images so its like
aa brand
1
2 "the string i sent"
the list has allways one more empty record before my record...
trying to see wtf is happening i counted the list size just before i send it
int f = list.getModel().getSize();
System.out.print(f);
and the answer is 2 ... if i enter 3 records its 6 .. etc...
i narrowed the problem to the model since changing the addBrand() method to
public void addBrand() {
String all = "xghxc";
model.addElement(all);
}
impudently shows two of "xghxc" being added to my list at the same time in front of my very own amazed eyes
i searched google but it doesnt even have a similar problem to mine :(
what i need is a code or an advice or smth to point me to not adding an empty useless record amongst my records
here is my full code for anyone who has the patience and time
MyMain.java
package tweGraf;
import javax.swing.JFrame;
public class MyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gui g = new Gui();
DB.MakePool();
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.setSize(1000, 800);
g.setVisible(true);
}
}
Gui.java
package tweGraf;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Gui extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frameYesNo = new JFrame();
String message = "all data will perish. are you sure";
private JPanel Container = new JPanel(); // panels
private JPanel FirstPanel = new JPanel();
private JPanel NewSession = new JPanel();
private JPanel LoadSession = new JPanel();
private JPanel LoadList = new JPanel();
private JPanel GraphSub1 = new JPanel();
private JPanel GraphSub2 = new JPanel();
private JPanel GraphSub3 = new JPanel();
private JTabbedPane GraphPanel = new JTabbedPane();
private JButton NewSessBtn = new JButton(); // buttons
private JButton LoadSessBtn = new JButton();
private JButton BackFP = new JButton();
private JButton plusBrand = new JButton();
private JButton minusBrand = new JButton();
private JButton Next = new JButton();
private JLabel EnterBrandLbl = new JLabel(
"Please insert brands for analysis "); // Labels
private JTextField BrandLbl = new JTextField(20); // textfields
public DefaultListModel<String> model = new DefaultListModel<String>
public JList BrandList = new JList(model); // list
private JScrollPane MyScrollPane = new JScrollPane(BrandList);
private CardLayout cardLayout = new CardLayout(); // layouts
private GridBagLayout MyLayout = new GridBagLayout();
GridBagConstraints MyConstr = new GridBagConstraints();
public Gui() {
super("twegraph");
NewSessBtn.setText("New Session"); // button configuration
LoadSessBtn.setText("Load Session");
BackFP.setText("Back");
plusBrand.setText("+");
minusBrand.setText("-");
Next.setText("Next");
actionListener al = new actionListener();
NewSessBtn.addActionListener(al); // add action listeners
LoadSessBtn.addActionListener(al);
BackFP.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Next.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Container.setLayout(cardLayout); // panels to container+
Container.add(FirstPanel, "FirstPanel");
Container.add(NewSession, "NewSession");
Container.add(LoadSession, "LoadSession");
Container.add(GraphPanel, "GraphPanel");
Container.add(LoadList, "LoadList");
FirstPanel.setLayout(MyLayout); // first panel
MyConstr.gridwidth = 3;
MyConstr.gridheight = 3;
MyConstr.weightx = 1.0;
MyConstr.weighty = 1.0;
MyConstr.ipadx = 100;
MyConstr.ipady = 50;
MyConstr.insets = new Insets(50, 20, 50, 20);
MyConstr.gridx = 1;
MyConstr.gridy = 0;
MyConstr.anchor = GridBagConstraints.NORTH;
MyLayout.setConstraints(NewSessBtn, MyConstr);
FirstPanel.add(NewSessBtn);
MyConstr.gridx = 1;
MyConstr.gridy = 2;
MyConstr.anchor = GridBagConstraints.SOUTH;
MyLayout.setConstraints(LoadSessBtn, MyConstr);
FirstPanel.add(LoadSessBtn);
NewSession.setLayout(MyLayout); // New Session panel
MyConstr.gridwidth = 3;
MyConstr.gridheight = 3;
MyConstr.ipadx = 0; // size
MyConstr.ipady = 0; // size
MyConstr.gridx = 0;
MyConstr.gridy = 2;
MyConstr.insets = new Insets(10, 20, 10, 20);
MyConstr.anchor = GridBagConstraints.SOUTHWEST;
MyLayout.setConstraints(BackFP, MyConstr);
NewSession.add(BackFP);
MyConstr.anchor = GridBagConstraints.SOUTHEAST;
MyLayout.setConstraints(Next, MyConstr);
NewSession.add(Next);
MyConstr.ipadx = 0; // size
MyConstr.ipady = 0; // size
MyConstr.gridx = 0; // place
MyConstr.gridy = 1; // place
MyConstr.insets = new Insets(0, 0, 0, 0);
MyConstr.anchor = GridBagConstraints.PAGE_START;
MyLayout.setConstraints(EnterBrandLbl, MyConstr);
NewSession.add(EnterBrandLbl);
MyConstr.gridx = 0;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.CENTER;
MyLayout.setConstraints(BrandLbl, MyConstr);
NewSession.add(BrandLbl);
MyConstr.gridx = 2;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.LAST_LINE_START;
MyLayout.setConstraints(plusBrand, MyConstr);
NewSession.add(plusBrand);
MyConstr.gridx = 2;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.LAST_LINE_END;
MyLayout.setConstraints(minusBrand, MyConstr);
NewSession.add(minusBrand);
MyConstr.ipadx = 0; // size
MyConstr.ipady = 0;
MyConstr.gridx = 0;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.SOUTH;
MyLayout.setConstraints(MyScrollPane, MyConstr);
NewSession.add(MyScrollPane);
GraphPanel.addTab("overall",GraphSub1); //Graph panel
GraphPanel.addTab("tweets/time",GraphSub2);
GraphPanel.addTab("fame",GraphSub3);
this.setContentPane(Container);
cardLayout.show(Container, "FirstPanel");
}
public class actionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();
int answer = 0;
if (src.equals(NewSessBtn))
{
answer = JOptionPane.showConfirmDialog(frameYesNo, message);
if (answer == JOptionPane.YES_OPTION) {
cardLayout.show(Container, "NewSession");
try {
DB.flushData();
} catch (SQLException ex) {
Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (answer == JOptionPane.NO_OPTION) {
frameYesNo.dispose();
}
}
if (src.equals(LoadSessBtn)){
cardLayout.show(Container, "LoadSession");
}
if (src.equals(BackFP)){
cardLayout.show(Container, "FirstPanel");
}
if (src.equals(Next)){
cardLayout.show(Container, "GraphPanel");
DB.sendArraytoDB(BrandList);
}
if (src.equals(plusBrand)){
addBrand();
}
if (src.equals(minusBrand))
{
removeBrand();
}
}
}
public void addBrand() {
/*int index = BrandList.getSelectedIndex(); // get selected index
if (index == -1) { // no selection, so insert at beginning
index = 0;
}
else { // add after the selected item
index++;
}*/
String all = "xghxc";
//model.insertElementAt(BrandLbl.getText(), index);
model.addElement(all);
//BrandLbl.setText(null);
}
public void removeBrand() {
int index2 = BrandList.getSelectedIndex();
if (index2 != -1){
model.remove(index2);
}
int size = model.getSize();
if (size == 0) {
minusBrand.setEnabled(false);
} else {
//if (index == model.getSize()) {
//index--;
//}
}
}
}
DB.java
package tweGraf;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JList;
/**
*
* #author cheval
*/
public class DB {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/twegrahpdb";
static final String USER = "root";
static final String PASS = "Xrt38H0a";
private static ComboPooledDataSource cdps = new ComboPooledDataSource();
public static void MakePool(){
try {
cdps = new ComboPooledDataSource();
cdps.setDriverClass(JDBC_DRIVER);
cdps.setJdbcUrl(DB_URL);
cdps.setUser(USER);
cdps.setPassword(PASS);
cdps.setMaxPoolSize( 50 );
cdps.setMaxStatements(50);
}catch(Exception ex){
System.out.printf("error smth wrong happened");
}
}
public static Connection getConnection() throws SQLException{
return cdps.getConnection();
}
public static void flushData() throws SQLException{
Statement stm = null;
Connection con = null;
try{
con = DB.getConnection();
stm = con.createStatement();
String flushquery1 = "TRUNCATE json_cache";
String flushquery2 = "TRUNCATE tweets";
String flushquery3 = "TRUNCATE tweet_mentions";
String flushquery4 = "TRUNCATE tweet_tags";
String flushquery5 = "TRUNCATE tweet_urls";
String flushquery6 = "TRUNCATE users";
String flushquery7 = "TRUNCATE brand_names";
stm.executeUpdate(flushquery1);
stm.executeUpdate(flushquery2);
stm.executeUpdate(flushquery3);
stm.executeUpdate(flushquery4);
stm.executeUpdate(flushquery5);
stm.executeUpdate(flushquery6);
stm.executeUpdate(flushquery7);
}catch (SQLException e) {
System.out.printf("error executing db clear");
} finally {
if (stm != null){
try{
stm.close();
System.out.printf("statement closed successfuly \n");
} catch (SQLException e){
System.out.printf("error closing statement");
}
}
if (con != null){
try{
con.close();
System.out.printf("connection closed succesfully \n");
} catch (SQLException e){
System.out.printf("error closing connection");
}
}
}
}
public static void sendArraytoDB(JList<String> list){
Connection con = null;
PreparedStatement stm = null;
String updQuery = "insert into brand_names (name) values (?)";
try{
con = DB.getConnection();
//con.setAutoCommit(false);
int x =1;
stm = con.prepareStatement(updQuery);
int f = list.getModel().getSize();
System.out.print(f);
for (int i=0; i<list.getModel().getSize(); i++){
String name =list.getModel().getElementAt(i);
stm.setString(x, name);
//try{
stm.executeUpdate();
//}finally{
//stm.close();
//}
}
}catch(SQLException ex){
System.out.printf("error while sending array to db");
ex.printStackTrace();
}finally{
if (stm != null){
try {
stm.close();
} catch (SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null){
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
if you still dont know dont care about my actual problem but STILL see smth wrong regarding my coding style or my techniques plz post it
thanks for your time
i narrowed the problem to the model since changing the addBrand() method to...
So this tells me the addBrand() method is called multiple times.
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Next.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
As you can see above you add the listener twice to the button.
I'm making a simple program that show the teams, the matches and racking goal of Euro2016 in France.
I have some problem with JTable when changing query.
Here is what happens:
when I change from a Table of (for example) 10 rows to another one that contains only 5 rows it works. But if I change from a table that contains 5 rows to another of 10, the table doesn't change, it displays only 5 rows.
Here the code:
public class Euro2016GUI extends JFrame {
private Container container;
private Sfondo pnlSfondo;
JTable table;
JPanel panel;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
static Vector<String> headers = new Vector<String>();
public Euro2016GUI() {
data.removeAll(data);
headers.removeAll(headers);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.setTitle("Euro2016");
this.setLocationRelativeTo(null);
pnlSfondo = new Sfondo();
container = this.getContentPane();
container.add(pnlSfondo);
}
public void createTable(String pQuery) {
data.removeAll(data);
headers.removeAll(headers);
Control control = new Control();
panel = new JPanel(new BorderLayout());
panel.setSize(300, 300);
panel.setBackground(Color.red);
control.getData(pQuery);
data = control.getData();
headers = control.getHeaders();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setMaximumSize(new Dimension(100, 300));
header_size();
JScrollPane scroll = new JScrollPane(table);
//scroll.setSize(600, 400);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.getContentPane().add(panel);
panel.add(scroll, BorderLayout.CENTER);
}
public void header_size() {
int colonne = table.getColumnModel().getColumnCount();
TableColumn column;
for (int i = 0; i < colonne; i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(200);
}
}
public void cleanData() {
if (table != null) {
DefaultTableModel dm = (DefaultTableModel) table.getModel();
dm.setRowCount(0);
table.revalidate();
}
data.removeAll(data);
headers.removeAll(headers);
}
}
CLASS CONTROL
public class Control {
private static Vector<Vector<String>> data = new Vector<Vector<String>>();
private static Vector<String> headers = new Vector<String>();
public void getData(String pQuery) {
// Enter Your MySQL Database Table name in below Select Query.
String query = pQuery;
Connection con = null;
ResultSet rs;
Statement st = null;
int colonne = 0;
data.removeAll(data);
headers.removeAll(headers);
try {
con = DBConnectionPool.getConnection();
st = con.createStatement();
rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
colonne = rsmd.getColumnCount();
for (int i = 1; i <= colonne; i++) {
headers.add(rsmd.getColumnName(i));
}
while (rs.next()) {
Vector<String> d = new Vector<String>();
for (int i = 1; i <= colonne; i++) {
d.add(rs.getString(i));
}
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataInJTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
DBConnectionPool.releaseConnection(con);
}
}
}
public Vector<Vector<String>> getData() {
return this.data;
}
public Vector<String> getHeaders() {
return this.headers;
}
}
HERE THE ACTION LISTENER IN THE MENU:
...
//----ROSE---//
private class OnClickRose implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
str = str.replace("[", "");
str = str.replace("]", "");
String sx = "'";
String dx = "'";
String query = query2.concat(sx.concat(str.concat(dx)));
//frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query);
}
}
//----CALENDARIO----//
private class OnClickCalendario implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query4);
}
}
//----CLASSIFICA MARCATORI----//
private class OnClickMarcatori implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query3);
}
}
...
Could anybody tell me where I wrong?
Basically to tell the table to refresh itself, you just call the method fireTableDataChanged() of it's table model.
So in your example, after you run the query, you could just call:
((DefaultTableModel)yourTable.getModel()).fireTableDataChanged();
But I suggest you to stop using default table model, and implement your own table model. It's a lot easier to work.
I have a class A and a class B.
In class A there is a constructor:
public A() {
getSelectedRow();
}
This constructor calls:
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
Up to here everything works fine!
The class B then calls the method getSelectedRow() like that:
A results = new A();
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
I just want to find out the selected table row from class A. The problem is that I am getting a null pointer exception and i dont know why. if I dont call the method everything works fine.
CLASS A:
public class AllResultsFromDB extends JFrame {
#SuppressWarnings("compatibility:9056676689615464658")
private static final long serialVersionUID = 188850508334531506L;
GUI ins = new GUI();
JTable table;
public AllResultsFromDB(GUI x) {
final Vector columnNames = new Vector();
final Vector data = new Vector();
this.ins = x;
try {
/** Initializing GUI class
* in order to call
* getSelectedTable() method. **/
Login sgui = new Login();
String dburl = "jdbc:oracle:thin:#localhost:1521:ORCL";
Connection connection = DriverManager.getConnection(dburl, sgui.getUsername(), sgui.getPassword());
// Fetch data from table specified by user
String query = "SELECT * FROM " + ins.getSelectedTable() + " ORDER BY id";
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData metad = rset.getMetaData();
int columns = metad.getColumnCount();
// This loop gets the names of the columns
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metad.getColumnName(i));
}
// This loop gets the data inside the rows
while (rset.next()) {
final Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rset.getObject(i));
}
data.addElement(row);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
table = new JTable(data, columnNames) {
public boolean isCellEditable(int row, int col) {
return false;
}
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object obj = getValueAt(row, column);
if (obj != null) {
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
table.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseReleased(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseEntered(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseExited(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseClicked(MouseEvent e) {
getSelectedRow();
if (e.getClickCount() == 2) {
//System.out.println(table.getSelectedRow());
Profile profile = new Profile();
try {
profile.getData();
//wait(500000);
profile.getImage();
} catch (Exception f) {
}
profile.setVisible(true);
}
}
});
} catch (SQLException e) {
}
}
public AllResultsFromDB(int x) {
x = getSelectedRow();
System.out.println(table.getSelectedRow());
}
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
}
CLASS B:
public class Profile extends JFrame {
AllResultsFromDB results = new AllResultsFromDB();
public Profile(AllResultsFromDB x) {
this.results=x;
try {
getData();
getImage();
} catch (Exception e) {
e.printStackTrace();
}
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getImage() throws Exception {
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
public void getData() throws Exception {
String url = "jdbc:oracle:thin:#localhost:1521:ORCL";
String username = "c##lambros";
String password = "16111111";
Connection conn = null;
try {
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT foto FROM criminals WHERE id = 5";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
//String name = resultSet.getString(1);
//System.out.println("Name = " + name);
File image = new File("java.jpg");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[256];
//
// Get the binary stream of our BLOB data
//
InputStream is = resultSet.getBinaryStream(1);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
private void jbInit() throws Exception {
this.setSize(new Dimension(816, 380));
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
}
In the classB since you are creating a new instance
A results = new A();
The value present in the table.getSelectedRow() also gets created newly and will point to null.
So make sure that you do somthing
A results = new A(selectedRow);
and in the constructor of the A,pass the argument to the function
getSelectedRow(selectedRow);
Please note : Make sure that the value of the "table.selectedRow" is maintained
If table is your instance variable in Class A then it might not be initialized when you are trying to access it in constructor of A.
And calling getSelectedRow from the constructor is not making any sense too.
Try to initialize the table variable in constructor instead of calling that method, it should work after it.
This is because the table object is not being initialized.
Try to initialize the table object in constructor....it is a good practice
This is a JDBC project. Data from a mySql database on a WAMP server is displayed in jtable. Now I want that user-entered ID on my Spinnerbutton and to delete row with that ID. I made a SQL Query and everything works, but the data on the myjtable 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 think I haven't implemented FireTableModel correctly in my NapraviTablicu method, but 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("sun.jdbc.odbc.JdbcOdbcDriver");
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);
model.fireTableDataChanged();
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();
model.fireTableDataChanged();
}
private void IzvrsiQuery() {
Object sp = Spinner.getValue();
ID = sp.toString();
SqlQuery=SqlQuery+ID;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
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 = 1;
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 = 3;
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();
}
});
}
}
First, thank you very much for your answer!
When I use PreparedStatement I get this exception:
java.lang.ClassCastException: com.mysql.jdbc.StatementImpl cannot be
cast to java.sql.PreparedStatement
..so I must use classic Statement
Also I have tried to not create JTable every time, I just make model in my NapraviTablicu method, and later use that model in my constructor by simply adding it to table Tablica, but now the table is not showing any data. I don't know if I implemented your hints right way in my code...
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 void 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);
//model.fireTableDataChanged();
}
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();
//model.fireTableDataChanged();
}
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", "");
PreparedStatement Stat = (PreparedStatement) 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=new JTable(model);
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 = 1;
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 = 3;
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();
}
});
}
}
You need to use com.mysql.jdbc.Driver as your JDBC driver rather than the generic JDBC/ODBC one. Also there's no need to call fireTableDataChanged, your TableModel will call this under the hood.
Side Notes:
No need to create the JTable every time. DefaultTableModel is a mutable TableModel which can be updated.
PreparedStatement is considered safer than Statement
There's no need to extend JFrame if you're not adding new functionality. A direct instance is preferred.
For maintainability consider keeping your database/non UI code separate from your UI code.
Update:
To create a PreparedStatement, use Connection#prepareStatement rather than Connection#createStatement.
PreparedStatement Stat = con2.prepareStatement(SqlQuery);
Then when executing the query, it is necessary to use the execute statement with the empty
argument list:
int rez = stat.executeUpdate();
Also better to place Statement & Connection & close statements in a finally block.
Java uses an initial lowercase letter for variables names which would make SqlQuery sqlQuery.