Any way to connect JTable (TableModel) with H2 database [duplicate] - java

This question already has answers here:
How to fill data in a JTable with database?
(7 answers)
Closed 7 years ago.
My current project is some kind of a database system that has a gui for maintenance. Before my major code rewrite, I used to serialize and de-serialize the TableModel to save and load data to the gui. Because this was not a good solution for obvious reasons I did some research and ended up using an H2 (local) database to save and load my data from.
The code used to save the data into my database can be found in my other question.
The save process itself is not the biggest problem but I can't find any good way to load the data back into my JTable (TableModel).
Is there any way to directly wire JTable (TableModel) together with any kind of SQL database? Currently using JTable with a database seems to be a really big hassle with Java.

Okay, so this is a simple example, which creates a in-memory database, with a single table and some values.
It uses a simple custom TableModel which can be "refreshed" if the underlying data is changed.
Have a closer look at JDBC Database Access for some more details
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class TestTable {
private Connection con;
public static void main(String[] args) {
new TestTable();
}
public TestTable() {
try {
Class.forName("org.h2.Driver");
String url = "jdbc:h2:mem:InMemoryTest";
con = DriverManager.getConnection(url);
createShoppingListTable();
fillShoppingListTable();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
} catch (ClassNotFoundException | SQLException exp) {
exp.printStackTrace();
}
}
protected void createShoppingListTable() throws SQLException {
String query = "create table shoppingList (id bigint identity, item varchar(255), quantity int)";
try (Statement stmt = con.createStatement()) {
stmt.execute(query);
}
}
protected void fillShoppingListTable() throws SQLException {
String[] items = {"Bananas", "Apples", "Grapes", "Pears", "Oranges"};
Random rnd = new Random();
try (PreparedStatement ps = con.prepareStatement("insert into shoppingList (item, quantity) values (?, ?)")) {
for (String item : items) {
ps.setString(1, item);
ps.setInt(2, rnd.nextInt(100));
ps.addBatch();
}
ps.executeBatch();
}
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
TestTableModel model = new TestTableModel();
JTable table = new JTable(model);
add(new JScrollPane(table));
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
model.refresh();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
}
}
public class TestTableModel extends AbstractTableModel {
private List<ShoppingList> shoppingList = new ArrayList<>(25);
private List<String> columnNames = new ArrayList<>(25);
#Override
public int getRowCount() {
return shoppingList.size();
}
#Override
public int getColumnCount() {
return columnNames.size();
}
#Override
public String getColumnName(int column) {
return columnNames.get(column);
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
ShoppingList rowValue = shoppingList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = rowValue.getId();
break;
case 1:
value = rowValue.getItem();
break;
case 2:
value = rowValue.getQuanity();
break;
}
return value;
}
public void refresh() throws SQLException {
List<String> values = new ArrayList<>(25);
try (PreparedStatement ps = con.prepareStatement("select * from shoppingList")) {
try (ResultSet rs = ps.executeQuery()) {
ResultSetMetaData md = rs.getMetaData();
for (int col = 0; col < md.getColumnCount(); col++) {
values.add(md.getColumnName(col + 1));
}
while (rs.next()) {
ShoppingList list = new ShoppingList(rs.getLong(1), rs.getString(2), rs.getInt(3));
shoppingList.add(list);
}
}
} finally {
if (columnNames.size() != values.size()) {
columnNames = values;
fireTableStructureChanged();
} else {
fireTableDataChanged();
}
}
}
public class ShoppingList {
private long id;
private String item;
private int quanity;
public ShoppingList(long id, String item, int quanity) {
this.id = id;
this.item = item;
this.quanity = quanity;
}
public long getId() {
return id;
}
public String getItem() {
return item;
}
public int getQuanity() {
return quanity;
}
}
}
}

Related

Deleting rows with right click from MySql table in JTable

I have a Java class as shown below which displays my table from my database. I want to add a function that will open a pop-up menu and delete row from table. How can i do that?
import java.awt.BorderLayout;
import javax.swing.*;
import java.sql.*;
import java.util.Vector;
public class Test {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = st.executeQuery(s);
ResultSetMetaData rsmt = rs.getMetaData();
int c = rsmt.getColumnCount();
Vector column = new Vector(c);
for (int i = 1; i <= c; i++) {
column.add(rsmt.getColumnName(i));
}
Vector data = new Vector();
Vector row = new Vector();
while (rs.next()) {
row = new Vector(c);
for (int i = 1; i <= c; i++) {
row.add(rs.getString(i));
}
data.add(row);
}
JFrame frame = new JFrame();
frame.setSize(500, 600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JTable table = new JTable(data, column);
JScrollPane jsp = new JScrollPane(table);
panel.setLayout(new BorderLayout());
panel.add(jsp, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setVisible(true);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
} finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
}
And as a reference i looked to this page but i couldn't bind method from here.
I found an example and i took it as a reference.
I got to handle and rewrite the code as 3 classes shown below:
JTablePopupMenuExample.java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class JTablePopupMenuExample extends JFrame implements ActionListener {
private JTable table;
private DefaultTableModel tableModel;
private JPopupMenu popupMenu;
private JMenuItem menuItemAdd;
private JMenuItem menuItemRemove;
private JMenuItem menuItemRemoveAll;
List<SentMessagesTable> msgList;
public JTablePopupMenuExample() throws Exception{
super("JTable Popup Menu Example");
// sample table data
String[] columnNames = new String[] {"id", "receiver", "sender", "msg_text", "status", "x_date"};
msgList = new ArrayList<SentMessagesTable>();
ResultSet rs = getTableRows();
while (rs.next()) {
SentMessagesTable msg = new SentMessagesTable();
msg.setId(rs.getInt("id"));
msg.setReceiver(rs.getString("receiver"));
msg.setSender(rs.getString("sender"));
msg.setMsgText(rs.getString("msg_text"));
msg.setStatus(rs.getString("status"));
msg.setxDate(rs.getString("x_date"));
msgList.add(msg);
}
String[][] rowDataTable = new String[34400][6];
for(int i = 0 ; i < msgList.size();i++) {
//burda jtable listesini doldur
rowDataTable[i][0] = String.valueOf(msgList.get(i).getId());
rowDataTable[i][1] = msgList.get(i).getReceiver();
rowDataTable[i][2] = msgList.get(i).getSender();
rowDataTable[i][3] = msgList.get(i).getMsgText();
rowDataTable[i][4] = msgList.get(i).getStatus();
rowDataTable[i][5] = msgList.get(i).getxDate();
}
// constructs the table with sample data
tableModel = new DefaultTableModel(rowDataTable, columnNames);
table = new JTable(tableModel);
// constructs the popup menu
popupMenu = new JPopupMenu();
menuItemAdd = new JMenuItem("Add New Row");
menuItemRemove = new JMenuItem("Remove Current Row");
menuItemRemoveAll = new JMenuItem("Remove All Rows");
menuItemAdd.addActionListener(this);
menuItemRemove.addActionListener(this);
menuItemRemoveAll.addActionListener(this);
popupMenu.add(menuItemAdd);
popupMenu.add(menuItemRemove);
popupMenu.add(menuItemRemoveAll);
// sets the popup menu for the table
table.setComponentPopupMenu(popupMenu);
table.addMouseListener(new TableMouseListener(table));
// adds the table to the frame
add(new JScrollPane(table));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800,1000);
setLocationRelativeTo(null);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new JTablePopupMenuExample().setVisible(true);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void actionPerformed(ActionEvent event) {
JMenuItem menu = (JMenuItem) event.getSource();
if (menu == menuItemAdd) {
addNewRow();
} else if (menu == menuItemRemove) {
removeCurrentRow();
} else if (menu == menuItemRemoveAll) {
removeAllRows();
}
}
private void addNewRow() {
tableModel.addRow(new String[0]);
}
private void removeCurrentRow(){
int selectedRow = table.getSelectedRow();
tableModel.removeRow(selectedRow);
String jdbcUrl = "jdbc:mysql://localhost/sms";
String username = "root";
String password = "";
String sql = "delete from sent_messages where id = '"+msgList.get(selectedRow).getId()+"'";
// java.sql.Statement stmt = null;
try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
java.sql.Statement stmt = conn.createStatement();) {
stmt.executeUpdate(sql);
System.out.println("Record deleted successfully");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void removeAllRows() {
int rowCount = tableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
tableModel.removeRow(0);
}
}
private ResultSet getTableRows() throws SQLException {
Connection con = null;
java.sql.Statement st = null;
ResultSet rs = null;
String s;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
st = con.createStatement();
s = "select * from sent_messages";
rs = ((java.sql.Statement) st).executeQuery(s);
}catch(Exception e) {
System.out.println(e.toString());
}
finally {
//con.close();
}
return rs;
}
}
SentMessagesTable.java which involves (getters and setters)
public class SentMessagesTable {
int id;
String receiver;
String sender;
String msgText;
String status;
String xDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getSender() {
return sender;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getMsgText() {
return msgText;
}
public void setMsgText(String msgText) {
this.msgText = msgText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getxDate() {
return xDate;
}
public void setxDate(String xDate) {
this.xDate = xDate;
}
}
And TableMouse Listener.java
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTable;
public class TableMouseListener extends MouseAdapter {
private JTable table;
public TableMouseListener(JTable table) {
this.table = table;
}
#Override
public void mousePressed(MouseEvent event) {
// selects the row at which point the mouse is clicked
Point point = event.getPoint();
int currentRow = table.rowAtPoint(point);
table.setRowSelectionInterval(currentRow, currentRow);
}
}
With that code i was able to delete records from JTable and also from my database.

Display ResultSet of a SQL query in a JTable (Java)

I'm working on a program with which I can search through a database and display the results.
I'm stuck at the displaying part at the moment. My SQL query already works and returns the results. I'm using a PreparedStatement to fill my ResultSet. However I don't know how I can return the data of the ResultSet to a JTable which I want to use to display the data. Can anyone explain to me in detail how to do this or if there is a better way instead of a JTable I'm not seeing?
I'm using the MVC model and the DAO pattern, but I'm still pretty new to programming.
So far from researching it I found the best solution to be to make a custom table class, but from there on I don't know how to progress.
My custom table class:
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class ResultSetTable {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
//Spaltennamen
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
//Alle Zeilen
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
And the relevant part of my View class:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import dbconnect.dao.impl.BTRDaoImpl;
public class View extends JFrame{
public View() {
JTable table = new JTable(new ResultSetTable(BTRDaoImpl.resultset);
this.setSize(600, 400);
setResizable(false);
}
My BTRDaoImpl class with the sql query and resultset:
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import mvc.View;
import dao.BTRbDao;
import business.BTRBean;
public class BTRDaoImpl extends AbstractDao implements BTRDao {
private Connection dbConnection = null;
private PreparedStatement preparedStatement = null;
public void sqlquery() {
try {
String btrname = View.searchbbtrname.getText();
String btrplz = View.searchbtrplz.getText();
btrname = btrname.trim().toUpperCase();
btrplz = btrplz.trim().toUpperCase();
if (btrplz.isEmpty()) {
String btrResult = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ FROM BP.TBBBST WHERE BBSTNABEG = ?";
dbConnection = AbstractDao.getConnection();
preparedStatement = dbConnection.prepareStatement(btrResult);
preparedStatement.setString(1, btrname);
} else {
String btrResult = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ FROM BP.TBBBST WHERE BBSTNABEG = ? AND BBSTPLZ = ?";
dbConnection = AbstractDao.getConnection();
preparedStatement = dbConnection.prepareStatement(btrResult);
preparedStatement.setString(1, btrname);
preparedStatement.setString(2, btrplz);
}
} catch (SQLException e1) {
System.out.println("An error with the SQL query occured: ");
e1.printStackTrace();
}
}
public Collection<BtrBean> getBTR() throws SQLException,
IOException {
sqlquery();
final Collection<BtrBean> result = new ArrayList<BtrBean>();
ResultSet resultset = null;
try {
resultset = preparedStatement.executeQuery();
// while loop to get data
while (resultset.next()) {
BtrBean btr = new BtrBean();
int btrid = resultset.getInt(1);
String btrplz = resultset.getString(3);
String btrname = resultset.getString(2);
btr.setBetriebnr(btrid);
btr.setBetriebplz(btrplz);
btr.setBetriebname(btrname);
result.add(btr);
// System.out.println("BTR-ID: " + btrid + " BTR PLZ: " + btrplz + " BTR: " + btrname);
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("An error processing the SQL occured: ");
e.printStackTrace();
} catch (NullPointerException npe) {
System.out.println("NullPointerException: ");
npe.printStackTrace();
} finally {
if (preparedStatement != null) preparedStatement.close();
closeConnection(resultset);
}
return result;
}
}
My BTRBean class:
public class BetriebBean {
private String betriebname;
private int betriebnr;
private String betriebplz;
public BetriebBean() {
}
public BetriebBean(String betriebname, int betriebnr, String betriebplz) {
super();
this.betriebname = betriebname;
this.betriebnr = betriebnr;
this.betriebplz = betriebplz;
}
public String getBetriebname() {
return betriebname;
}
public void setBetriebname(String betriebname) {
this.betriebname = betriebname;
}
public int getBetriebnr() {
return betriebnr;
}
public void setBetriebnr(int betriebnr) {
this.betriebnr = betriebnr;
}
public String getBetriebplz() {
return betriebplz;
}
public void setBetriebplz(String betriebplz) {
this.betriebplz = betriebplz;
}
}
//edit:
My whole View.class:
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
public class View extends JFrame{
private static final long serialVersionUID = 1L;
public static final String SEARCH = "SEARCH";
private JLabel searchbtrlabel = new JLabel("BTR name:");
public static JTextField searchbtrname = new JTextField(10);
private JLabel searchbtrlabel = new JLabel("PLZ:");
public static JTextField searchbtrplz = new JTextField(10);
private JButton searchbutton = new JButton();
public View() {
this.setTitle("BTR search TBBBST");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.add(searchbtrlabel);
this.add(searchbtrname);
this.add(searchbtrplzlabel);
this.add(searchbtrplz);
searchbutton.setText("Search");
searchbutton.setActionCommand(View.SEARCH);
this.add(searchbutton);
JTable table = new JTable();
this.add(table);
this.setSize(600, 400);
setResizable(false);
//this.pack();
}
public JTextField getSearchbtrname() {
return searchbetriebname;
}
public JTextField getSearchbbtrplz() {
return searchbetriebplz;
}
public JButton getSearchbutton() {
return searchbutton;
}
}
My Controller class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import mvc.Model;
import dbconnect.dao.impl.BTRDaoImpl;
public class Controller implements Observer, ActionListener{
private Model model;
#SuppressWarnings("unused")
private View view;
public Controller(Model model, View view) {
this.model = model;
this.view = view;
model.addObserver(this);
view.getSearchbutton().addActionListener(this);
view.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case View.SEARCH:
model.search();
view.table.setModel(ResultSetToTable.buildTableModel(BTRDaoImpl.resultset));
break;
default:
System.out.println("Error : " + e.getActionCommand());
break;
}
}
#Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
}
Firstly, include rs2xml.jar in your libraries. You can find it here
In whatever action to populate your MySQL query in your JTable use following general idea:
public void sqlquery() {
try {
String btrResult = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ FROM BP.TBBBST WHERE BBSTNABEG = ?";
preparedStatement = dbConnection.prepareStatement(btrResult);
dbConnection.setString(1, btrname);
ResultSet rs =dbConnection.executeQuery();
Ur_table_name.setModel(DbUtils.resultSetToTableModel(DbUtils.resultSetToel(rs)); //this line of code will show it in your JTable
}catch(Exception e){
}
What is your question? Try being more specific than "[...] but from there on I don't know how to progress." What do you want to do? Are the results from your query visible in the table?
Using the answer from Paul Vargas over here Most simple code to populate JTable from ResultSet, you could start with something like this (using Java 8):
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;
public class ResultSetToTable {
public static void main(final String[] arguments) {
SwingUtilities.invokeLater(() -> {
try {
new ResultSetToTable().createAndShowGui();
} catch (SQLException e) {
e.printStackTrace();
}
});
}
private void createAndShowGui() throws SQLException {
final JFrame frame = new JFrame("Stack Overflow");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JPanel panel = new JPanel();
final TableModel tableModel = buildTableModel(getData("Audi"));
final JTable table = new JTable(tableModel);
panel.add(new JScrollPane(table));
frame.getContentPane().add(panel);
frame.setVisible(true);
}
private ResultSet getData(final String btrName) throws SQLException {
final String url = "jdbc:h2:/Freek/TBBBST";
final Connection connection = DriverManager.getConnection(url, "me", "123");
final String sql = "SELECT BBSTBBNR, BBSTNABE, BBSTPLZ " +
"FROM BP.TBBBST " +
"WHERE BBSTNABEG = ?";
final PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, btrName);
return preparedStatement.executeQuery();
}
/**
* See https://stackoverflow.com/a/10625471/1694043
*/
public static TableModel buildTableModel(final ResultSet resultSet)
throws SQLException {
int columnCount = resultSet.getMetaData().getColumnCount();
// Column names.
Vector<String> columnNames = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
columnNames.add(resultSet.getMetaData().getColumnName(columnIndex));
}
// Data of the table.
Vector<Vector<Object>> dataVector = new Vector<>();
while (resultSet.next()) {
Vector<Object> rowVector = new Vector<>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
rowVector.add(resultSet.getObject(columnIndex));
}
dataVector.add(rowVector);
}
return new DefaultTableModel(dataVector, columnNames);
}
}
For older versions of Java, you should be able to use this version of the main method:
public static void main(final String[] arguments) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ResultSetToTable().createAndShowGui();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
Edit: connecting controller and table
To make the table available outside the view, you need to convert the table variable in the View() constructor into a field (like you have done with searchbtrname) and create a getTable getter method for it (like you have done with getSearchbtrname). In the Controller.actionPerformed method you can now change view.table into view.getTable().

How do i get the id of the cell click using JTable?

I am using a JTable to display data from my database. What I want to happen is that when a row is clicked it opens another window.
My Code
Connection to the database
public class JFrametest extends javax.swing.JFrame {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to Java Derby database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("EmailsDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "student", "student");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
out.println(cnfe);
} catch (SQLException sqle) {
out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
Displaying Data from the database
try {
String query = "select * from messages";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e) {
e.printStackTrace();
}
As anyone got any ideas on what i can do? is this possible?
You could use a mouseClicked Action Listener to do this.
You can use MouseListener for that, here is simple example:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TestFrame extends JFrame {
public static void main(String... s) {
new TestFrame();
}
private JTable t;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
DefaultTableModel model = new DefaultTableModel(0,2);
for(int i=0;i<10;i++){
model.addRow(new Object[]{i,"other info "+i});
}
model.setColumnIdentifiers(new Object[]{"id","info"});
t = new JTable(model);
t.addMouseListener(getListener());
add(new JScrollPane(t));
}
protected void showDialog(int rowAtPoint) {
Object valueAt = t.getValueAt(rowAtPoint, 0);
// other operations
JDialog d = new JDialog();
d.setTitle("id="+valueAt);
d.setModal(true);
d.setAlwaysOnTop(true);
d.setLocationRelativeTo(null);
d.pack();
d.setVisible(true);
}
private MouseListener getListener() {
return new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(e.getClickCount() >= 1){
int rowAtPoint = t.rowAtPoint(e.getPoint());
if(rowAtPoint != -1)
showDialog(rowAtPoint);
}
}
};
}
}

inserting java code from one class to another

So I have an interesting problem. I have an application that I wanted to have progress bars in each cell of the table. To be safe I wrote a stand alone app that does just what I want but now I'm having problems incorporating it into my pre-existing code. Im getting lost on what I need from each file. I.m posting the app table and the progress bar table code. I need to get these two two mesh or to puot it simply I need the progress bar in the app table. Any help appreciated.
application table
package gui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.AlgorithmParameters;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class FileTable extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTable table;
private DefaultTableModel tableModel =
new DefaultTableModel(new String[]
{"File", "Size", "Status" }, 0);
private File dir;
private File temp;
private JPopupMenu popup;
private String key;
private PasswordStorage passwordStorage;
private JFileChooser fileChooser;
private static String salt = "loquetdeliciouslysalty";
private static byte[] IV;
public FileTable() {
// Set Layout Manager
setLayout(new BorderLayout());
// Create Swing Components
table = new JTable();
table.setModel(tableModel);
table.setDropTarget(new TableDnD(table));
table.setShowGrid(false);
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setPreferredWidth(250);
passwordStorage = new PasswordStorage();
fileChooser = new JFileChooser();
popup = new JPopupMenu();
JMenuItem removeItem = new JMenuItem("Remove");
removeItem.setIcon(new ImageIcon("removeMenu.png"));
popup.add(removeItem);
// Add Components to pane
add(new JScrollPane(table), BorderLayout.CENTER);
table.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
table.getSelectionModel().setSelectionInterval(row, row);
if(e.getButton() == MouseEvent.BUTTON3) {
popup.show(table, e.getX(), e.getY());
}
}
});
removeItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int row = table.getSelectedRow();
if(row > -1) {
tableModel.removeRow(table.getSelectedRow());
}
}
});
}
public boolean isTableEmpty() {
if(tableModel.getRowCount() == 0) {
return true;
}
else {
return false;
}
}
public void addFile(File file) {
tableModel.addRow(
new Object[]{file, file.length() + " kb",Not Processed"});
}
public void removeFile() {
int[] rows = table.getSelectedRows();
for(int i = 0; i < rows.length; i++) {
tableModel.removeRow(rows[i]-i);
}
}
public void clearTable()
{
int rowCount = tableModel.getRowCount();
for(int i = 0; i < rowCount; i++) {
tableModel.removeRow(0);
}
table.removeAll();
}
}
The progress bar table
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class UpdateTable
{
public static void main(String[] args)
{
new UpdateTable();
}
public UpdateTable()
{
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException |
InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException ex) {
}
UpdatableTableModel model = new UpdatableTableModel();
JTable table = new JTable();
table.setModel(model);
table.getColumn("Status").setCellRenderer(new ProgressCellRender());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
FileFinderWorker worker = new FileFinderWorker(model);
worker.execute();
}
});
}
public class ProgressCellRender extends JProgressBar implements TableCellRenderer
{
#Override
public Component getTableCellRendererComponent(JTable
table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
int progress = 0;
if (value instanceof Float)
{
progress = Math.round(((Float) value) * 100f);
} else if (value instanceof Integer)
{
progress = (int) value;
}
setValue(progress);
return this;
}
}
public class RowData
{
private File file;
private String type;
private long length;
private float status;
public RowData(File file, String type)
{
this.file = file;
this.type = type;
this.length = file.length();
this.status = 0f;
}
public File getFile()
{
return file;
}
public long getLength()
{
return length;
}
public float getStatus()
{
return status;
}
public String getType()
{
return type;
}
public void setStatus(float status)
{
this.status = status;
}
}
public class UpdatableTableModel extends AbstractTableModel
{
private List<RowData> rows;
private Map<File, RowData> mapLookup;
public UpdatableTableModel()
{
rows = new ArrayList<>(25);
mapLookup = new HashMap<>(25);
}
#Override
public int getRowCount()
{
return rows.size();
}
#Override
public int getColumnCount()
{
return 4;
}
#Override
public String getColumnName(int column)
{
String name = "??";
switch (column) {
case 0:
name = "File";
break;
case 1:
name = "File Type";
break;
case 2:
name = "Size";
break;
case 3:
name = "Status";
break;
}
return name;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
RowData rowData = rows.get(rowIndex);
Object value = null;
switch (columnIndex)
{
case 0:
value = rowData.getFile();
break;
case 1:
value = rowData.getType();
break;
case 2:
value = rowData.getLength();
break;
case 3:
value = rowData.getStatus();
break;
}
return value;
}
#Override//new value //row to change //column to change
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
RowData rowData = rows.get(rowIndex);
switch (columnIndex)
{
case 3:
if (aValue instanceof Float)
{
rowData.setStatus((float) aValue);
}
break;
}
}
public void addFile(File file)
{
RowData rowData = new RowData(file, "A File");
mapLookup.put(file, rowData);
rows.add(rowData);
fireTableRowsInserted(rows.size() - 1, rows.size() - 1);
}
protected void updateStatus(File file, int progress)
{
RowData rowData = mapLookup.get(file);
if (rowData != null) {
int row = rows.indexOf(rowData);
float p = (float) progress / 100f;
setValueAt(p, row, 3);
fireTableCellUpdated(row, 3);
}
}
}
public class FileFinderWorker extends SwingWorker<List<File>, File>
{
private UpdatableTableModel model;
public FileFinderWorker(UpdatableTableModel model)
{
this.model = model;
}
#Override
protected void process(List<File> chunks) //data chunks
{
for (File file : chunks)
{
model.addFile(file);
}
}
#Override
protected List<File> doInBackground() throws Exception
{
String usrHome = "user.home"; // takes the entire home dir
// user.dir will use working directory
// (wherever you save your Java shit)
File files[] = new
File(System.getProperty(usrHome)).listFiles();//grabbing all files from directory.
List<File> lstFiles = new ArrayList<>(Arrays.asList(files));
for (File file : lstFiles)
{
publish(file);
}
return lstFiles;
}
#Override
protected void done()
{
try {
List<File> files = get();
for (File file : files)
{
new FileReaderWorker(model, file).execute();
}
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
public class FileReaderWorker extends SwingWorker<File, File>
{
private File currentFile;
private UpdatableTableModel model;
public FileReaderWorker(UpdatableTableModel model, File file)
{
this.currentFile = file;
this.model = model;
addPropertyChangeListener(new PropertyChangeListener()
{
#Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals("progress"))
{
FileReaderWorker.this.model.updateStatus(currentFile, (int) evt.getNewValue());
}
}
});
}
#Override
protected File doInBackground() throws Exception
{
if (currentFile.isFile())
{
setProgress(0);
long fileLength = currentFile.length();
BufferedReader reader = null;
char[] cbuf = new char[1024];//change this if everything loads too fast
try {
reader = new BufferedReader(new FileReader(currentFile));
int bytesRead = -1;
int totalBytesRead = 0;
while ((bytesRead = reader.read(cbuf)) != -1) {
totalBytesRead += bytesRead;
int progress = (int) Math.round(((double) totalBytesRead / (double) fileLength) *
100d);
setProgress(progress);
Thread.sleep(25);
}
setProgress(100);
} catch (Exception e) {
e.printStackTrace();
setProgress(100);
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
} else {
setProgress(100);
}
return currentFile;
}
}
}
progress bar needs to get into application
You should look into AOP aspectJ.
Using this you could do the task

Add ResultSet into Jtable (between two classes)

My application throws NullPointerException. I created connection between MySQL database and my second class.
I can't call DefaultTableModel by method in my second class.
How can I solve this problem?
public class MySQL extends javax.swing.JFrame {
private DefaultTableModel modelTabeli;
public MySQL(){
initComponents();
BazaDana bd = new BazaDana();
try{
modelTabeli = bd.map();
jTable1.setModel(modelTabeli);
}
catch(Exception e){
System.out.println(e.toString());
}
}
public static void main(String args[]) throws Exception{
BazaDana bd = new BazaDana();
bd.readDataBase();
}
}
Second class
import java.sql.*;
import javax.swing.table.DefaultTableModel;
public class BazaDana{
public DefaultTableModel map() throws SQLException
{
defaultTableModel = new DefaultTableModel();
int numberOfColumns = resultSetMetaData.getColumnCount();
while (resultSet.next())
{
Object [] rowData = new Object[numberOfColumns];
for (int i = 0; i < rowData.length; ++i)
{
rowData[i] = resultSet.getObject(i+1);
}
defaultTableModel.addRow(rowData);
}
return defaultTableModel;
}
}
Ok, may I give you an alternative solution if your goal is to separate GUI class from class which queries database. Don't return DefaultTableModel, return just values from ResultSet through some collection, like this:
Create MySql GUI class:
import java.awt.EventQueue;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class MySql extends JFrame{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"First column","Second column"});
public MySql(){
table.setModel(model);
add(new JScrollPane(table));
//Populate table
BazaDana bd = new BazaDana();
List<Value> values = bd.selectAll();
for(Value v : values){
model.addRow(new Object[]{v.getFirstValue(),v.getSecondValue()});
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run() {
MySql ms = new MySql();
ms.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ms.pack();
ms.setVisible(true);
}});
}
}
Then create Java bean class:
public class Value {
private int id;
private String firstValue;
private String secondValue;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstValue() {
return firstValue;
}
public void setFirstValue(String firstValue) {
this.firstValue = firstValue;
}
public String getSecondValue() {
return secondValue;
}
public void setSecondValue(String secondValue) {
this.secondValue = secondValue;
}
}
And finally your BazaDana class which queries database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class BazaDana {
public List<Value> selectAll(){
Connection conn = null;
Statement st = null;
ResultSet rs = null;
//Create list of values
List<Value> values = new ArrayList<Value>();
try{
Class.forName("com.mysql.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/nameofdb","user","pass");
st = conn.createStatement();
rs = st.executeQuery("SELECT * FROM mytable");
while(rs.next()){
Value v = new Value();
v.setFirstValue(rs.getString("first_column"));
v.setSecondValue(rs.getString("second_column"));
values.add(v);
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return values;
}
}

Categories