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
Related
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 the following cod!
when i call the fruitsTable() from refreshButton() it refreshes the JTable! but when i call it from another class it does not refresh the Table! bellow is the simplified code
public ResultSet sqlCommand(String sqlStatement) throws SQLException
{
this.sqlStatement = sqlStatement;
ConnectingToMysql fruitsConnection = new ConnectingToMysql();
Connection myConnection = fruitsConnection.ConnectingToMysql();
Statement st = myConnection.createStatement();
ResultSet result = st.executeQuery(sqlStatement);
return result;
}
public Vector<String> getColumnData() throws SQLException
{
ResultSetMetaData metaData = sqlCommand(sqlStatement).getMetaData();
int columnCount = metaData.getColumnCount();
Vector<String> allColumn = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
allColumn.add(metaData.getColumnName(i));
}
return allColumn;
}
public Vector<Vector<String>> getData() throws SQLException
{
ResultSet result = sqlCommand(sqlStatement);
ResultSetMetaData metaData = result.getMetaData();
int columnCount = metaData.getColumnCount();
Vector<Vector<String>> allRow = new Vector<Vector<String>>(columnCount);
while(result.next())
{
Vector<String> eachRow = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
eachRow.add(result.getString(i));
}
allRow.add(eachRow);
}
return allRow;
}
public JScrollPane fruitsTable() throws SQLException
{
Vector<String> columnData = getColumnData();
Vector<Vector<String>> rowData = getData();
fruitsTableModel.setDataVector(rowData,columnData);
Font font = new Font("Courier", Font.PLAIN,16);
fruitsTable = new JTable();
fruitsTable.setModel(fruitsTableModel);
fruitsTable.setPreferredScrollableViewportSize(new Dimension(850,310));
fruitsTable.setRowHeight(30);
fruitsTable.setFont(font);
JScrollPane fruitsScrollPane = new JScrollPane(fruitsTable);
dataValue();
return fruitsScrollPane;
}
private JButton refreshButton() throws SQLException
{
JButton refreshButton = new JButton("Refresh Record");
refreshButton.setPreferredSize(new Dimension(100,40));
refreshButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
fruitsTable();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
return refreshButton;
}
and this is the only code from the other class that calls the fruitsTable().
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
String number = numberTextField.getText();
int ID = Integer.parseInt(number);
String fruit = fruitTextField.getText();
String color = colorTextField.getText();
String taste = tasteTextField.getText();
System.out.println("The value is: " + number + " " + fruit + " " + color + " " + taste);
String sqlText = "Insert into fruits(ID,Fruit,Color,Tast) values(?,?,?,?)";
ConnectingToMysql connectingToMysql = new ConnectingToMysql();
Connection makeConnection = connectingToMysql.ConnectingToMysql();
PreparedStatement pdt = makeConnection.prepareStatement(sqlText);
pdt.setInt(1,ID);
if(fruit.isEmpty())
{
pdt.setNull(2,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(2,fruit);
}
if(color.isEmpty())
{
pdt.setNull(3,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(3,color);
}
if(taste.isEmpty())
{
pdt.setNull(4,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(4,taste);
}
pdt.executeUpdate();
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
}
catch(SQLIntegrityConstraintViolationException e)
{
JOptionPane.showMessageDialog(null, "The 'Number' you entered already exist!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
}
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
You're creating a new GetFruits object and refreshing it's table instead of updating the existing one. Try creating a class variable of GetFruits so you're using the same instance instead of creating a new one each time. Just guessing since I can't see all the code that contains the action listener.
I could really need your help, I tried to solve this problem for over one week, but haven't found a solution yet.
My Aim: I want to create a table, which can read the Data from a Database. I can also add Data to the DB by inserting it in my program.
My Problem: After inserting the Data i want the Database to refresh, so that it also shows my new record set. But no matter what i tried, it didn't work.
My Code: Here is my Mainframe-Class:
public class Gui_Test extends JFrame {
JButton addMovieButton;
JFrame frame = new JFrame("Movie Database");
JPanel panel;
JMenuBar menubar;
JMenu fileMenu;
JLabel label;
JTable table = new JTable();
MovieTableModel mtm;
public static void main(String[] args) {
Gui_Test test = new Gui_Test();
test.run();
}
public void run() {
// Gui ///
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setBackground(Color.black);
// Add - Movie Button ///
addMovieButton = new JButton("Add Movie");
addMovieButton.addActionListener(new addMovieButtonListener());
panel.add(addMovieButton);
// Table select ///
mtm = new MovieTableModel();
table.setModel(mtm);
JScrollPane pane = new JScrollPane(table);
frame.getContentPane().add(pane);
frame.getContentPane().add(BorderLayout.WEST, panel);
}
class addMovieButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddMoviePanel addmoviepanel = new AddMoviePanel();
addmoviepanel.moviepanel(mtm);
}
}}
Here is my TableModel:
public class MovieTableModel extends AbstractTableModel {
Connection con = null;
Vector columnNames = new Vector();
Vector data = new Vector();
ResultSet rs;
ResultSetMetaData meta;
public MovieTableModel() {
showResult();
}
void showResult() {
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/...", "sa",
"");
java.sql.Statement stmt = con.createStatement();
String query = "SELECT * FROM movies ORDER BY id DESC";
ResultSet rs = stmt.executeQuery(query);
meta = rs.getMetaData();
int columns = meta.getColumnCount();
// get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(meta.getColumnName(i));
}
// get row data
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
if (con != null)
try {
rs.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
#Override
public String getColumnName(int column) {
return columnNames.get(column).toString();
}
#Override
public int getColumnCount() {
try {
return meta.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
#Override
public Class getColumnClass(int column) {
// TODO Auto-generated method stub
return getValueAt(0, column).getClass();
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int row, int column) {
return ((Vector) data.get(row)).get(column);
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
void addRow(final String value1, final String value2, final String value3,
final String value4, final String value5, final String value6,
final String value7) {
try {
Connection con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/Jonas/workspace/movieDB", "sa",
"");
try {
final java.sql.Statement state = con.createStatement();
try {
state.addBatch("INSERT INTO movies VALUES (DEFAULT, '"
+ value1 + "', '" + value2 + "'," + value3 + ", '"
+ value4 + "', " + value5 + ", '" + value6 + "', '"
+ value7 + "')");
state.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}
And here is my addMovieFrame, which opens to add new Movies:
public class AddMoviePanel {
MovieTableModel mtm;
JPanel addMoviePanel;
JFrame addMovieFrame;
JTextField value1Input;
JTextField value2Input;
// ... value3 - value7
Connection con = null;
public void moviepanel(MovieTableModel mtm) {
this.mtm = mtm;
addMovieFrame = new JFrame("Add Movie");
addMovieFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMovieFrame.setVisible(true);
addMovieFrame.setSize(550, 300);
addMoviePanel = new JPanel();
GroupLayout layout = new GroupLayout(addMoviePanel);
addMoviePanel.setLayout(layout);
JLabel label1 = new JLabel("label1:");
JLabel label2 = new JLabel("label2");
// ...JLabel 3-7 same as Label 1&2
addMoviePanel.add(label1);
addMoviePanel.add(label2);
// ...add Label 3-7
value1Input = new JTextField();
value2Input = new JTextField();
// ... value3- value7 Input
addMoviePanel.add(value1Input);
addMoviePanel.add(value2Input);
// ... add value3Input - value7Input
JButton ok = new JButton("Ok");
ok.addActionListener(new okActionListener());
addMovieFrame.add(ok);
addMovieFrame.getContentPane().add(addMoviePanel);
// here was just Layout Stuff //
}
class okActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
mtm.addRow(value1Input.getText(), value2Input.getText()
// ... value3Input.getText() - value7Input.getText()
);
mtm.fireTableDataChanged();
addMovieFrame.dispose();
}
}}
I already tried several types and positions of fireXXX-Methods...
Maybe somebody got an idea, how to refresh my jtable, when hitting the OK-Button in my addMovie-Frame? :)
As shown here and discuseed here, only your TableModel should fire table model events. While this is typically done in setValueAt(), you can insert a whole row and fire a single event, as shown here.
I use DefaultTableModel for my JTable model, But not show my table!
public class RecordTableGUI2 extends JFrame {
JTable table;
RecordTableModel2 model2;
public RecordTableGUI2() {
model2 = new RecordTableModel2();
table = new JTable(model2);
add(new JScrollPane(table), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RecordTableGUI2();
}
});
}
}
Model Class:
public class RecordTableModel2 extends DefaultTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
Vector data = new Vector();
Vector column = new Vector();
public RecordTableModel2() {
try {
con = DriverManager.getConnection(dbUrl, "root", "2323");
statement = con.createStatement();
result = statement.executeQuery(query);
int c = result.getMetaData().getColumnCount();
for (int i = 1; i <= c; i++) {
column.add(result.getMetaData().getColumnName(i));
System.out.println(result.getMetaData().getColumnName(i)); //prints correct
}
while (result.next()) {
Vector eachRow = new Vector(c);
for (int i = 1; i <= c; i++) {
eachRow.add(result.getString(i));
System.out.println(result.getString(i)); //prints correct
}
data.add(eachRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
}
}
How to introduce vectors to DefaultTableModel?
Output just show a blank JFrame
Add this at first statement of constructor:
super(data,column);
And declare data and column as static
This program is used to read data from database. In the database,there are three tables pki17, pki18, pkn18. For viewing different tables,JComboBox is used and it works by changing the TableModel of the table. Also by using tableChanged method I made table editable. When a cell value in the table is changed the corresponding value in the database has to change to.
When I use tableChanged and actionPerformed methods together, value in database doesn’t get changed when I’m editing a cell in the swing table. When I remove actionPerformed method, then I can update database by editing table cells.
I need to have both abilities, to choose a table from the database by using JComboBox and update database values by editing values in the swing table.
I think the problem exists because TableModel of the table is changed in both methods. But I don’t know how to solve it.
public class TableCombobox extends JPanel implements ActionListener, TableModelListener {
static JTable table;
static JComboBox box;
static MyTableModel model;
static Connection con = null;
static Statement stmt = null;
public TableCombobox() throws SQLException {
super(new BorderLayout());
table = new JTable(new MyTableModel("pki18"));
table.setPreferredScrollableViewportSize(new Dimension(500, 400));
table.setFillsViewportHeight(true);
table.getModel().addTableModelListener(this);
JScrollPane scrollPane = new JScrollPane(table);
JPanel menuPanel = new JPanel();
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
menuPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1,
Color.black));
String[] dalykas = { "Chose groop", "pki17", "pki18", "pkn18" };
box = new JComboBox(dalykas);
box.setMaximumSize(new Dimension(150, 25));
box.setAlignmentX(Component.LEFT_ALIGNMENT);
box.addActionListener(this);
box.setSelectedIndex(2);
menuPanel.add(box);
JPanel cards = new JPanel(new CardLayout());
cards.add(scrollPane, "view");
add(menuPanel, BorderLayout.LINE_START);
add(cards, BorderLayout.CENTER);
}
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public void actionPerformed(ActionEvent event) {
JComboBox cb = (JComboBox) event.getSource();
String pav = (String) cb.getSelectedItem();
if (pav != "Chose groop") {
try {
model = new MyTableModel(pav);
table.setModel(model);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void GUI() throws SQLException {
JFrame frame = new JFrame("E-gradebook");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new TableCombobox());
frame.pack();
frame.setSize(800, 400);
frame.setVisible(true);
}
public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/pki18",
"root", "");
GUI();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
}
}
static Connection getConnection() {
return con;
}
}
public class ImportData {
static Connection con = TableCombobox.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
con.setAutoCommit(false);
stmt = con.createStatement();
stmt.addBatch("update pki18 set " + stulpPav + " = " + duom
+ " where studento_id = " + studId + ";");
stmt.executeBatch();
con.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
con.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
static int rowCount;
static Object data [][];
static String columnNames [];
public MyTableModel(String grupName) throws SQLException{
String query ="select Studento_id, vardas_pavarde, 1_semestras,"+
" 2_semestras, egzaminas, bendras_balas "+
"from pki18." + grupName;
ResultSet rs ;
Connection con = TableCombobox.getConnection();
Statement stmt = null;
stmt = con.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][6];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getLong("Studento_id");
data[iEil][1] = rs.getString("Vardas_Pavarde");
data[iEil][2] = rs.getByte("1_semestras");
data[iEil][3] = rs.getByte("2_semestras");
data[iEil][4] = rs.getByte("Egzaminas");
data[iEil][5] = rs.getByte("bendras_balas");
}
String[] columnName = {"Asmens_kodas","Vardas_Pavarde","1_Semestras"
,"2_Semestras","Egzaminas","Bendras_Balas"};
columnNames = columnName;
}
public int getColumnCount(){
return columnNames.length;
}
public int getRowCount(){
return data.length;
}
public String getColumnName(int col){
return columnNames[col];
}
public Object getValueAt(int row, int col){
return data[row][col];
}
public Class getColumnClass(int col){
return getValueAt(0, col).getClass();
}
public boolean isCellEditable(int row, int col){
return true;
}
public void setValueAt(Object value, int row, int col){
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
In the constructor, you add the table model listener to the current model only:
table.getModel().addTableModelListener(this);
In the action event, however, you replace the table model:
model = new MyTableModel(pav);
table.setModel(model);
As a consequence, the new table model won't have the listener, and you won't receive notifications any more. Have the actionPerformed method add the listener as well, and your problem should be fixed.