JTable refreshed data not displayed - java

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.

Related

JTable using abstracttablemodel not updating after insert

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.

I can't make my program to wait until GUI has finished gathering requested info (Java)

I am quite new to Java and before I end up asking this question I searched and searched SO, but I don't seem to get my head around it.
As you will see I have a class that creates a GUI, asks for some input and stores that input in a returnable String[].
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class InputConsole {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static String[] details = new String[3];
public static JButton btn2013;
public static JButton btn2014;
public static JButton btn2015;
public static JButton btn2016;
public static JButton btnGo;
public static JTextField textField2;
public static JTextField textField4;
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
c.fill = GridBagConstraints.HORIZONTAL;
}
btn2013 = new JButton("ZMR 2013");
btn2013.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2013";
btn2014.setEnabled(false);
btn2015.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
if (shouldWeightX) {
c.weightx = 0.0;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 0;
c.gridy = 0;
pane.add(btn2013, c);
btn2014 = new JButton("ZMR 2014");
btn2014.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2014";
btn2013.setEnabled(false);
btn2015.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 0, 0);
c.weightx = 0.0;
c.gridx = 1;
c.gridy = 0;
pane.add(btn2014, c);
btn2015 = new JButton("ZMR 2015");
btn2015.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2015";
btn2013.setEnabled(false);
btn2014.setEnabled(false);
btn2016.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 2;
c.gridy = 0;
pane.add(btn2015, c);
btn2016 = new JButton("ZMR 2016");
btn2016.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[2] = "2016";
btn2013.setEnabled(false);
btn2014.setEnabled(false);
btn2015.setEnabled(false);
textField2.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.0;
c.gridx = 3;
c.gridy = 0;
pane.add(btn2016, c);
JLabel textField1 = new JLabel("What was your Bib number? : ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
pane.add(textField1, c);
textField2 = new JTextField(10);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[0] = textField2.getText();
textField4.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 2;
pane.add(textField2, c);
JLabel textField3 = new JLabel("What is your email address : ");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 2;
pane.add(textField3, c);
textField4 = new JTextField(15);
textField4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
details[1] = textField4.getText();
btnGo.setEnabled(true);
btnGo.requestFocusInWindow();
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 3;
pane.add(textField4, c);
btnGo = new JButton("Go And Get Me My Diploma!");
btnGo.setEnabled(false);
btnGo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, details[0] + " " + details[1] + " " + details[2]);
}
});
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0;
c.weighty = 1.0;
c.anchor = GridBagConstraints.PAGE_END;
c.insets = new Insets(10, 0, 0, 0);
c.gridx = 0;
c.gridwidth = 4;
c.gridy = 4;
pane.add(btnGo, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Zagori Mountain Running Diploma Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setSize(500, 250);
frame.setVisible(true);
}
public String[] inputBib() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
return details;
}
But when I call this GUI in another class
public class CheckFiles {
InputConsole bibInput = new InputConsole();
String[] detailsInput = bibInput.inputBib();
private static Scanner scanner;
public String bibCorrected() {
String yearToCheck = null;
{
if (detailsInput[2] == "2016") {
yearToCheck = "ZMR2016.txt";
} else if (detailsInput[2] == "2015") {
yearToCheck = "ZMR2015.txt";
} else if (detailsInput[2] == "2014") {
yearToCheck = "ZMR2014.txt";
} else {
yearToCheck = "ZMR2013.txt";
in order to obtain that String[], I get a java.lang.NullPointerException. I Know that I get this because the program does not wait for the GUI to get all the input and files the returnable String[] as null. I think I know that I have to do something with wait() and notify() but I do not seem to understand exactly what.
Thank you in advance for any suggestions. (and very sorry for the long thread)
You could add a button on your GUI which will just call the bibCorrected() method. Currently you are showing and then returning so the array is empty and arg 2 is none existent therefor throwing an NPE. This would probably be the easiest way to resolve the issue.
Also, it's better to use String.equals(String) rather than ==. Read this StackOverflow post What is the difference between == vs equals() in Java?

How to use fireTableRowsInserted with CachedRowSet for inserting new row in JTable?

I'm trying to insert new row in the table from a form (composed of text fields ) with CachedRowSet data structure in JTable using a button. The class creating the GIU (including the buttons, namely CoffeesFrame.java ) is as following,
public class CoffeesFrame extends JFrame implements RowSetListener {
private static Connection myConn = null;
private static String url = null;
private static String username = null;
private static String password = null;
private static JTable table; // The table for displaying data
private static JFrame frame;
private static JLabel label_COF_NAME;
private static JLabel label_SUP_ID;
private static JLabel label_PRICE;
private static JLabel label_SALES;
private static JLabel label_TOTAL;
private static JTextField textField_COF_NAME;
private static JTextField textField_SUP_ID;
private static JTextField textField_PRICE;
private static JTextField textField_SALES;
private static JTextField textField_TOTAL;
private static JButton button_ADD_ROW;
private static JButton button_UPDATE_DATABASE;
private static JButton button_DISCARD_CHANGES;
CoffeesTableModel ctModel;
public CoffeesFrame() {
url = "jdbc:mysql://localhost:3306/myDemo";
username = "student";
password = "student";
}
protected void createAndShowGUI(Connection con) throws SQLException {
con.setAutoCommit(false);
System.out.println("The GUI started");
frame = new JFrame();
frame.setTitle("My Coffee Frame");
CachedRowSet crSet = getContentsOfCoffeesTable(con);
ctModel = new CoffeesTableModel(crSet);
ctModel.addEventHandelersToRowsSet(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
try {
myConn.close();
}
catch (SQLException sl) {
sl.printStackTrace();
}
System.exit(0);
}
});
/*
String[] columnNames = { "First Name", "Last Name", "Sport",
"# of Years", "Vegetarian" };
Object[][] data = {
{ "Kathy", "Smith", "Snowboarding", new Integer(5),
new Boolean(false) },
{ "John", "Doe", "Rowing", new Integer(3), new Boolean(true) },
{ "Sue", "Black", "Knitting", new Integer(2),
new Boolean(false) },
{ "Jane", "White", "Speed reading", new Integer(20),
new Boolean(true) },
{ "Joe", "Brown", "Pool", new Integer(10), new Boolean(false) } };
// table = new JTable(data, columnNames);
*/
table = new JTable();
table.setModel(ctModel);
label_COF_NAME = new JLabel();
label_SUP_ID = new JLabel();
label_PRICE = new JLabel();
label_SALES = new JLabel();
label_TOTAL = new JLabel();
textField_COF_NAME = new JTextField(10);
textField_SUP_ID = new JTextField(10);
textField_PRICE = new JTextField(10);
textField_SALES = new JTextField(10);
textField_TOTAL = new JTextField(10);
button_ADD_ROW = new JButton();
button_UPDATE_DATABASE = new JButton();
button_DISCARD_CHANGES = new JButton();
label_COF_NAME.setText("Coffee Name:");
label_SUP_ID.setText("Supplier ID:");
label_PRICE.setText("Price:");
label_SALES.setText("Sales:");
label_TOTAL.setText("Total Sales:");
textField_COF_NAME.setText("Enter new coffee name");
textField_SUP_ID.setText("101");
textField_PRICE.setText("0");
textField_SALES.setText("0");
textField_TOTAL.setText("0");
button_ADD_ROW.setText("Add row to table");
button_UPDATE_DATABASE.setText("Update database");
button_DISCARD_CHANGES.setText("Discard changes");
Container pane = getContentPane();
pane.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
pane.setLayout(new GridBagLayout());
GridBagConstraints cons = new GridBagConstraints();
cons.fill = GridBagConstraints.BOTH;
cons.anchor = GridBagConstraints.CENTER;
cons.weightx = 0.5;
cons.weighty = 1.0;
cons.gridx = 0;
cons.gridy = 0;
cons.gridwidth = 2;
pane.add(new JScrollPane(table), cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_START;
cons.weightx = 0.25;
cons.weighty = 0;
cons.gridx = 0;
cons.gridy = 1;
cons.gridwidth = 1;
pane.add(label_COF_NAME, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_END;
cons.weightx = 0.75;
cons.weighty = 0;
cons.gridx = 1;
cons.gridy = 1;
cons.gridwidth = 1;
pane.add(textField_COF_NAME, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.weightx = 0.25;
cons.weighty = 0;
cons.anchor = GridBagConstraints.LINE_START;
cons.gridx = 0;
cons.gridy = 2;
cons.gridwidth = 1;
pane.add(label_SUP_ID, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_END;
cons.weightx = 0.75;
cons.weighty = 0;
cons.gridx = 1;
cons.gridy = 2;
cons.gridwidth = 1;
pane.add(textField_SUP_ID, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_START;
cons.weightx = 0.25;
cons.weighty = 0;
cons.gridx = 0;
cons.gridy = 3;
cons.gridwidth = 1;
pane.add(label_PRICE, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_END;
cons.weightx = 0.75;
cons.weighty = 0;
cons.gridx = 1;
cons.gridy = 3;
cons.gridwidth = 1;
pane.add(textField_PRICE, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_START;
cons.weightx = 0.25;
cons.weighty = 0;
cons.gridx = 0;
cons.gridy = 4;
cons.gridwidth = 1;
pane.add(label_SALES, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_END;
cons.weightx = 0.75;
cons.weighty = 0;
cons.gridx = 1;
cons.gridy = 4;
cons.gridwidth = 1;
pane.add(textField_SALES, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_START;
cons.weightx = 0.25;
cons.weighty = 0;
cons.gridx = 0;
cons.gridy = 5;
cons.gridwidth = 1;
pane.add(label_TOTAL, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_END;
cons.weightx = 0.75;
cons.weighty = 0;
cons.gridx = 1;
cons.gridy = 5;
cons.gridwidth = 1;
pane.add(textField_TOTAL, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_START;
cons.weightx = 0.5;
cons.weighty = 0;
cons.gridx = 0;
cons.gridy = 6;
cons.gridwidth = 1;
pane.add(button_ADD_ROW, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_END;
cons.weightx = 0.5;
cons.weighty = 0;
cons.gridx = 1;
cons.gridy = 6;
cons.gridwidth = 1;
pane.add(button_UPDATE_DATABASE, cons);
cons.fill = GridBagConstraints.HORIZONTAL;
cons.anchor = GridBagConstraints.LINE_START;
cons.weightx = 0.5;
cons.weighty = 0;
cons.gridx = 0;
cons.gridy = 7;
cons.gridwidth = 1;
pane.add(button_DISCARD_CHANGES, cons);
button_ADD_ROW.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// System.out.println("The add row");
JOptionPane.showMessageDialog(frame, textField_COF_NAME.getText()+" "+
Integer.parseInt(textField_SUP_ID.getText().trim())+" "+
Float.parseFloat(textField_PRICE.getText().trim())+" "+
Integer.parseInt(textField_SALES.getText().trim())+" "+
Integer.parseInt(textField_TOTAL.getText().trim()));
try {
ctModel.insertRow(textField_COF_NAME.getText(),
Integer.parseInt(textField_SUP_ID.getText().trim()),
Float.parseFloat(textField_PRICE.getText().trim()),
Integer.parseInt(textField_SALES.getText().trim()),
Integer.parseInt(textField_TOTAL.getText().trim()));
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
});
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
private CachedRowSet getContentsOfCoffeesTable(Connection con)
throws SQLException {
CachedRowSet cr = null;
try {
cr = new CachedRowSetImpl();
cr.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
cr.setConcurrency(ResultSet.CONCUR_UPDATABLE);
cr.setUsername(username);
cr.setPassword(password);
cr.setUrl(url);
cr.setCommand("select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES");
cr.execute();
}
catch (Exception ex) {
ex.printStackTrace();
}
return cr;
}
#Override
public void rowSetChanged(RowSetEvent event) {
}
#Override
public void rowChanged(RowSetEvent event) {
}
#Override
public void cursorMoved(RowSetEvent event) {
}
public static void main(String[] args) throws SQLException {
CoffeesFrame cf = new CoffeesFrame();
try {
myConn = DriverManager.getConnection(url, username, password);
if (myConn != null) {
System.out.println("The app is connected with the database");
}
else {
System.out.println("The connection is not established");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
// launch the swing app
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
cf.createAndShowGUI(myConn);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
It uses CoffeesTableModel.java for data modeling as following,
public class CoffeesTableModel extends AbstractTableModel {
public static CachedRowSet coffeeRowSet;
public static java.sql.ResultSetMetaData rsMetaData;
public static int ncolms, nrows;
public CoffeesTableModel(CachedRowSet crSet) throws SQLException {
this.coffeeRowSet = crSet;
this.rsMetaData = this.coffeeRowSet.getMetaData();
ncolms = rsMetaData.getColumnCount();
this.coffeeRowSet.beforeFirst();
this.nrows = 0;
while (this.coffeeRowSet != null & this.coffeeRowSet.next()) {
nrows++;
}
this.coffeeRowSet.beforeFirst();
}
public void addEventHandelersToRowsSet(RowSetListener rsListener) {
this.coffeeRowSet.addRowSetListener(rsListener);
}
public void insertRow(String coffeeName, int supplierID, float price,
int sales, int total) throws SQLException {
try {
this.coffeeRowSet.moveToInsertRow();
this.coffeeRowSet.updateString("COF_NAME", coffeeName);
this.coffeeRowSet.updateInt("SUP_ID", supplierID);
this.coffeeRowSet.updateFloat("PRICE", price);
this.coffeeRowSet.updateInt("SALES", sales);
this.coffeeRowSet.updateInt("TOTAL", total);
this.coffeeRowSet.insertRow();
this.coffeeRowSet.moveToCurrentRow();
fireTableRowsInserted(coffeeRowSet.getRow()-1, coffeeRowSet.getRow()-1);
// I get SQL error after un-commenting this line
// this.coffeeRowSet.acceptChanges();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void close() {
try {
coffeeRowSet.getStatement().close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public String getColumnName(int columnIndex) {
String colName = null;
try {
colName = this.rsMetaData.getColumnLabel(columnIndex + 1);
} catch (Exception ex) {
ex.toString();
}
return colName;
}
#Override
public int getRowCount() {
return nrows;
}
#Override
public int getColumnCount() {
return ncolms;
}
public Class getColumnClass(int column) {
return String.class;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object o = new Object();
try {
this.coffeeRowSet.absolute(rowIndex + 1);
o = this.coffeeRowSet.getObject(columnIndex + 1);
}
catch (SQLException ex) {
ex.printStackTrace();
}
if (o == null){
return null;
}
else{
return o.toString();
}
}
public boolean isEdible(int rowIndex , int colIndex ){
return false;
}
public void setValueAt(Object o, int col, int row ){
System.out.println();
}}
JOptionPane shows the data after pushing the "Add row to table" button, but, no data is inserted in the table. How can I improve the code ?
Now that you have added more code to your question, I am wondering why you want to use the CachedRowSet interface (see for example CachedRowSet: can it still be used to hold ResultSet data? and CachedRowSet slower than ResultSet?). I would consider retrieving the data from the database and storing it in regular objects or a table model.
For the table model, you can also use the DefaultTableModel class. This has the advantage that a default implementation has been created for all methods, which makes your work a lot easier. It is probably a good idea to separate the table model as much as possible from the database access.
You could copy all coffee data from the database to the DefaultTableModel instance and close the database connection (you can even do this outside of the table model class). Later, you can start a new database connection when you want to update the database (for example by deleting all the old records and inserting all the current records; you can retrieve the current records in the table model using the getDataVector method).
A table model class could look like this:
import java.sql.*;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
public class CoffeesTableModelV2 extends DefaultTableModel {
public CoffeesTableModelV2(Vector data, Vector columnNames) {
super(data, columnNames);
}
public void insertRow(String coffeeName, int supplierID, float price,
int sales, int total) {
final Vector<Object> rowVector = new Vector<>();
rowVector.add(coffeeName);
rowVector.add(supplierID);
rowVector.add(price);
rowVector.add(sales);
rowVector.add(total);
addRow(rowVector);
}
#Override
//public boolean isEdible(int rowIndex, int colIndex) {
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
#Override
public void setValueAt(Object o, int col, int row) {
final String message = "should not be called for a read-only table model";
throw new RuntimeException("CoffeesTableModelV2.setValueAt " + message);
}
public static CoffeesTableModelV2 createTableModel(ResultSet resultSet)
throws SQLException {
return new CoffeesTableModelV2(getData(resultSet), getColumnNames(resultSet));
}
private static Vector<Vector<Object>> getData(ResultSet resultSet)
throws SQLException {
Vector<Vector<Object>> data = new Vector<>();
int columnCount = resultSet.getMetaData().getColumnCount();
while (resultSet.next()) {
Vector<Object> rowVector = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
rowVector.add(resultSet.getObject(columnIndex));
}
data.add(rowVector);
}
return data;
}
private static Vector<String> getColumnNames(ResultSet resultSet)
throws SQLException {
Vector<String> columnNames = new Vector<>();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
columnNames.add(metaData.getColumnName(columnIndex));
}
return columnNames;
}
}

Defaultlistmodel adds twice an item from jtextfield

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.

Tutoring Log, Confuse don code for a JButton

The purpose of this program is to allow the tutor to keep a log of his/her students. I'm a newbie to GUI so my code probably isnt the best but I need help with the code for the JButton "SAVE" to take all the information in the log and store it in a .txt file. Line 374 is where my button command is.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
// Declare variables:
// array lists
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor"};
Object[][] data = new Object[25][5];
// table
JTable table = new JTable(data, columnNames) {
// sets the ability of the cells to be edited by the user
#Override
public boolean isCellEditable(int row, int column) {
return false; // returns false, cannot be edited
}
};
// frames
JFrame frame, frame1;
// panels
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
// labels
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp;
// text fields
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp;
// buttons
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
// additionals
int keyCode, rowIndex, rowNumber, noOfStudents;
// button handler
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
// setting/modifying table components
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
// main buttons
btnAdd = new JButton("ADD");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false); // disables the component
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false); // disables the component
btnSort = new JButton("SORT");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
// with button Listeners
// sub buttons
btnAddInput = new JButton("Add");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
// set label names
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("COURSE");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
// set text fields width
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15)); // limits the length of input:
// max of 15
txtID.addKeyListener(keyListener); // accepts only numerals
// main frame
// panel for the table
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
// panel for the main buttons
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// positions the main buttons
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Student Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
// ADD frame
// panel for adding
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
// positions the components for adding
// labels
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
// panel for other necessary buttons
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}// end
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ADD")) {
// text fields for Student input data
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + ""); // will preview the ID
// input during Add
txtName.setText(data[rowIndex][1] + ""); // will preview the Name
// input during Add
txtCourse.setText(data[rowIndex][2] + ""); // will preview the
// Course input during
// Add
txtProfessor.setText(data[rowIndex][3] + ""); // will preview the Year
// input during Add
txtHelp.setText(data[rowIndex][4] + ""); // will preview the
// Gender input during
// Add
txtID.setEditable(false); // forbids the user to edit the entered
// ID number
frame1.setTitle("Edit Student data"); // title bar name for edit
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true); // sets the visibility of frame1
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
} catch (FileNotFoundException ex) {
}
}else if (e.getActionCommand().equals("Edit2")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "INCOMPLETE INPUT.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
frame1.dispose();
}
table.updateUI();
} else if (e.getActionCommand().equals("Cancel")) {
frame1.dispose();
}
}
}// end
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
You need to call flush() method once at the end of printing content to file.
Like,
else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("filename.txt");
out.println(txtID.getText());
out.println(txtName.getText());
out.println(txtCourse.getText());
out.println(txtProfessor.getText());
out.println(txtHelp.getText());
out.flush();
} catch (FileNotFoundException ex) {
}
}
The java.io.Writer.flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
The print method will call write method in class PrintWriter, piece of source code is as follows:
/**
* Prints a String and then terminates the line. This method behaves as
* though it invokes <code>{#link #print(String)}</code> and then
* <code>{#link #println()}</code>.
*
* #param x the <code>String</code> value to be printed
*/
public void println(String x) {
synchronized (lock) {
print(x);
println();
}
}
We can see in print() method, it will call write() method.
/**
* Prints a string. If the argument is <code>null</code> then the string
* <code>"null"</code> is printed. Otherwise, the string's characters are
* converted into bytes according to the platform's default character
* encoding, and these bytes are written in exactly the manner of the
* <code>{#link #write(int)}</code> method.
*
* #param s The <code>String</code> to be printed
*/
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}

Categories